JAVA 反射
目录[ Hide ]
类的加载概述和加载时机
类加载器的概述和分类
反射概述
Class.forName()读取配置文件举例
package com.heima.reflect;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* Code by pureqh on 2021-03-25
*/
public class Demo2_Reflect {
public static void main(String[] args) throws Exception {
/*//未用反射 只在说多态
Juicer j = new Juicer(); //购买榨汁机
j.run(new Apple()); //向榨汁机中放入苹果
j.run(new Orange()); //Fruit f = new Orange();*/
//用反射和配置文件
BufferedReader br = new BufferedReader(new FileReader("config.properties"));
Class clazz = Class.forName(br.readLine());
Fruit f = (Fruit) clazz.newInstance(); //父类引用指向子类对象
Juicer j = new Juicer();
j.run(f);
}
}
interface Fruit{
public void squeeze();
}
class Apple implements Fruit{
public void squeeze(){
System.out.println("榨出一杯苹果汁");
}
}
class Orange implements Fruit{
public void squeeze(){
System.out.println("榨出一杯橘子汁");
}
}
class Juicer{
/*public void run(Apple a){
a.squeeze();
}
public void run(Orange o){
o.squeeze();
}*/
public void run(Fruit f){
f.squeeze();
}
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* Code by pureqh on 2021-03-25
*/
public class Demo2_Reflect {
public static void main(String[] args) throws Exception {
/*//未用反射 只在说多态
Juicer j = new Juicer(); //购买榨汁机
j.run(new Apple()); //向榨汁机中放入苹果
j.run(new Orange()); //Fruit f = new Orange();*/
//用反射和配置文件
BufferedReader br = new BufferedReader(new FileReader("config.properties"));
Class clazz = Class.forName(br.readLine());
Fruit f = (Fruit) clazz.newInstance(); //父类引用指向子类对象
Juicer j = new Juicer();
j.run(f);
}
}
interface Fruit{
public void squeeze();
}
class Apple implements Fruit{
public void squeeze(){
System.out.println("榨出一杯苹果汁");
}
}
class Orange implements Fruit{
public void squeeze(){
System.out.println("榨出一杯橘子汁");
}
}
class Juicer{
/*public void run(Apple a){
a.squeeze();
}
public void run(Orange o){
o.squeeze();
}*/
public void run(Fruit f){
f.squeeze();
}
}
config.properties
com.heima.reflect.Apple
通过反射获取带参构造方法并使用
package com.heima.reflect;
import com.heima.bean.Person;
import java.lang.reflect.Constructor;
/**
* Code by pureqh on 2021-03-26
*/
public class Demo3_Constructor {
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("com.heima.bean.Person");
/*Person p = (Person) clazz.newInstance(); //通过无参构造创建对象
System.out.println(p);*/
Constructor c = clazz.getConstructor(String.class,int.class); //获取有参构造
Person p = (Person) c.newInstance("张三",23); //通过有参构造创建对象
System.out.println(p);
}
}
import com.heima.bean.Person;
import java.lang.reflect.Constructor;
/**
* Code by pureqh on 2021-03-26
*/
public class Demo3_Constructor {
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("com.heima.bean.Person");
/*Person p = (Person) clazz.newInstance(); //通过无参构造创建对象
System.out.println(p);*/
Constructor c = clazz.getConstructor(String.class,int.class); //获取有参构造
Person p = (Person) c.newInstance("张三",23); //通过有参构造创建对象
System.out.println(p);
}
}
通过反射获取成员变量并使用
package com.heima.reflect;
import com.heima.bean.Person;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
/**
* Code by pureqh on 2021-03-26
*/
public class Demo4_Field {
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("com.heima.bean.Person");
Constructor c = clazz.getConstructor(String.class,int.class);
Person p = (Person) c.newInstance("张三",23);
/*Field f = clazz.getField("name");
f.set(p,"李四");*/
Field f = clazz.getDeclaredField("name"); //通过暴力反射获取字段
f.setAccessible(true);
f.set(p,"李四");
System.out.println(p);
}
}
import com.heima.bean.Person;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
/**
* Code by pureqh on 2021-03-26
*/
public class Demo4_Field {
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("com.heima.bean.Person");
Constructor c = clazz.getConstructor(String.class,int.class);
Person p = (Person) c.newInstance("张三",23);
/*Field f = clazz.getField("name");
f.set(p,"李四");*/
Field f = clazz.getDeclaredField("name"); //通过暴力反射获取字段
f.setAccessible(true);
f.set(p,"李四");
System.out.println(p);
}
}
通过反射获取方法并使用
package com.heima.reflect;
import com.heima.bean.Person;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
* Code by pureqh on 2021-03-26
*/
public class Demo5_method {
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("com.heima.bean.Person");
Constructor c = clazz.getConstructor(String.class,int.class);
Person p = (Person) c.newInstance("张三",23);
Method m = clazz.getMethod("eat"); //获取eat方法
m.invoke(p);
Method m2 = clazz.getMethod("eat",int.class);
m2.invoke(p, 10);
}
}
import com.heima.bean.Person;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
* Code by pureqh on 2021-03-26
*/
public class Demo5_method {
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("com.heima.bean.Person");
Constructor c = clazz.getConstructor(String.class,int.class);
Person p = (Person) c.newInstance("张三",23);
Method m = clazz.getMethod("eat"); //获取eat方法
m.invoke(p);
Method m2 = clazz.getMethod("eat",int.class);
m2.invoke(p, 10);
}
}
通过反射越过泛型检查
package com.heima.test;
import java.lang.reflect.Method;
import java.util.ArrayList;
/**
* Code by pureqh on 2021-03-26
* 泛型只在编译器有效,在运行期会被擦除掉
*/
public class Test1 {
public static void main(String[] args) throws Exception {
ArrayList<Integer> list = new ArrayList<>();
list.add(111);
Class clazz = Class.forName("java.util.ArrayList"); //获取字节码对象
Method m = clazz.getMethod("add",Object.class); //获取add方法
m.invoke(list,"abc");
System.out.println(list);
}
}
import java.lang.reflect.Method;
import java.util.ArrayList;
/**
* Code by pureqh on 2021-03-26
* 泛型只在编译器有效,在运行期会被擦除掉
*/
public class Test1 {
public static void main(String[] args) throws Exception {
ArrayList<Integer> list = new ArrayList<>();
list.add(111);
Class clazz = Class.forName("java.util.ArrayList"); //获取字节码对象
Method m = clazz.getMethod("add",Object.class); //获取add方法
m.invoke(list,"abc");
System.out.println(list);
}
}
通过反射写一个通用的设置某个对象的某个属性为指定的值
package com.heima.test;
import java.lang.reflect.Field;
/**
* Code by pureqh on 2021-03-26
*/
public class Tool {
//此方法可以将obj对象中名未propertyName属性的值设置为value
public void setProperty(Object obj, String property, Object value) throws Exception {
Class clazz = obj.getClass(); //获取字节码对象
Field f = clazz.getDeclaredField(property); //暴力反射获取字段
f.setAccessible(true);
f.set(obj,value);
}
}
import java.lang.reflect.Field;
/**
* Code by pureqh on 2021-03-26
*/
public class Tool {
//此方法可以将obj对象中名未propertyName属性的值设置为value
public void setProperty(Object obj, String property, Object value) throws Exception {
Class clazz = obj.getClass(); //获取字节码对象
Field f = clazz.getDeclaredField(property); //暴力反射获取字段
f.setAccessible(true);
f.set(obj,value);
}
}
package com.heima.test;
/**
* Code by pureqh on 2021-03-26
*/
public class Test3 {
public static void main(String[] args) throws Exception {
Student s = new Student("张三",23);
System.out.println(s);
Tool t = new Tool();
t.setProperty(s,"name","李四");
System.out.println(s);
}
}
class Student{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
/**
* Code by pureqh on 2021-03-26
*/
public class Test3 {
public static void main(String[] args) throws Exception {
Student s = new Student("张三",23);
System.out.println(s);
Tool t = new Tool();
t.setProperty(s,"name","李四");
System.out.println(s);
}
}
class Student{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
练习
package com.heima.test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
/**
* Code by pureqh on 2021-03-26
*/
public class Test2 {
public static void main(String[] args) throws Exception {
//创建输入流关联配置文件
BufferedReader br = new BufferedReader(new FileReader("xxx.properties"));
Class clazz = Class.forName(br.readLine()); //读取配置文件中的类名,获取字节码对象
DemoClass dc = (DemoClass) clazz.newInstance(); //通过字节码对象创建对象
dc.run();
}
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
/**
* Code by pureqh on 2021-03-26
*/
public class Test2 {
public static void main(String[] args) throws Exception {
//创建输入流关联配置文件
BufferedReader br = new BufferedReader(new FileReader("xxx.properties"));
Class clazz = Class.forName(br.readLine()); //读取配置文件中的类名,获取字节码对象
DemoClass dc = (DemoClass) clazz.newInstance(); //通过字节码对象创建对象
dc.run();
}
}
xxx.properties
com.heima.test.DemoClass
动态代理的概述和实现
package com.heima.DynamicProxy;
/**
* Code by pureqh on 2021-03-28
*/
public interface Student {
public void login();
public void submit();
}
/**
* Code by pureqh on 2021-03-28
*/
public interface Student {
public void login();
public void submit();
}
package com.heima.DynamicProxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.StandardSocketOptions;
/**
* Code by pureqh on 2021-03-28
*/
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler(Object target){
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("权限校验");
method.invoke(target,args); //执行被代理target对象的方法
System.out.println("日志记录");
return null;
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.StandardSocketOptions;
/**
* Code by pureqh on 2021-03-28
*/
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler(Object target){
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("权限校验");
method.invoke(target,args); //执行被代理target对象的方法
System.out.println("日志记录");
return null;
}
}
package com.heima.DynamicProxy;
import sun.applet.Main;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
/**
* Code by pureqh on 2021-03-28
*/
public class Test {
public static void main(String[] args) {
/*UserImp ui = new UserImp();
ui.add();
ui.delete();*/
/**/
System.out.println("--------------------");
/*MyInvocationHandler m = new MyInvocationHandler(ui);
User u = (User) Proxy.newProxyInstance(ui.getClass().getClassLoader(),ui.getClass().getInterfaces(),m);
u.add();
u.delete();*/
StudentImp si = new StudentImp();
si.login();
si.submit();
System.out.println("--------------------");
MyInvocationHandler m = new MyInvocationHandler(si);
Student s = (Student) Proxy.newProxyInstance(si.getClass().getClassLoader(),si.getClass().getInterfaces(),m);
s.login();
s.submit();
}
}
import sun.applet.Main;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
/**
* Code by pureqh on 2021-03-28
*/
public class Test {
public static void main(String[] args) {
/*UserImp ui = new UserImp();
ui.add();
ui.delete();*/
/**/
System.out.println("--------------------");
/*MyInvocationHandler m = new MyInvocationHandler(ui);
User u = (User) Proxy.newProxyInstance(ui.getClass().getClassLoader(),ui.getClass().getInterfaces(),m);
u.add();
u.delete();*/
StudentImp si = new StudentImp();
si.login();
si.submit();
System.out.println("--------------------");
MyInvocationHandler m = new MyInvocationHandler(si);
Student s = (Student) Proxy.newProxyInstance(si.getClass().getClassLoader(),si.getClass().getInterfaces(),m);
s.login();
s.submit();
}
}
Template模板设计模式概述和使用
package com.heima.Template;
/**
* Code by pureqh on 2021-03-28
*/
public class Demo1_Template {
public static void main(String[] args) {
/*long start = System.currentTimeMillis();
for (int i = 0;i<100;i++){
System.out.println("*");
}
long end = System.currentTimeMillis();
System.out.println(end - start);*/
Demo d = new Demo();
System.out.println(d.getTime());
}
}
abstract class GetTime{
public final long getTime(){
long start = System.currentTimeMillis();
code();
long end = System.currentTimeMillis();
return end - start;
}
public abstract void code();
}
class Demo extends GetTime{
@Override
public void code() {
int i = 0;
while (i< 10000){
System.out.println("x");
i++;
}
}
}
/**
* Code by pureqh on 2021-03-28
*/
public class Demo1_Template {
public static void main(String[] args) {
/*long start = System.currentTimeMillis();
for (int i = 0;i<100;i++){
System.out.println("*");
}
long end = System.currentTimeMillis();
System.out.println(end - start);*/
Demo d = new Demo();
System.out.println(d.getTime());
}
}
abstract class GetTime{
public final long getTime(){
long start = System.currentTimeMillis();
code();
long end = System.currentTimeMillis();
return end - start;
}
public abstract void code();
}
class Demo extends GetTime{
@Override
public void code() {
int i = 0;
while (i< 10000){
System.out.println("x");
i++;
}
}
}
自己实现枚举类
package com.heima.enumeration;
/**
* Code by pureqh on 2021-03-28
*/
public class Week {
public static final Week MON = new Week();
public static final Week TUE = new Week();
public static final Week WED = new Week();
private Week(){} //私有构造,不让其他类创建本类对象
}
/**
* Code by pureqh on 2021-03-28
*/
public class Week {
public static final Week MON = new Week();
public static final Week TUE = new Week();
public static final Week WED = new Week();
private Week(){} //私有构造,不让其他类创建本类对象
}
package com.heima.enumeration;
/**
* Code by pureqh on 2021-03-28
*/
public class Week2 {
public static final Week2 MON = new Week2("星期一");
public static final Week2 TUE = new Week2("星期二");
public static final Week2 WED = new Week2("星期三");
private String name;
private Week2(String name){
this.name = name;
}
public String getName() {
return name;
}
}
/**
* Code by pureqh on 2021-03-28
*/
public class Week2 {
public static final Week2 MON = new Week2("星期一");
public static final Week2 TUE = new Week2("星期二");
public static final Week2 WED = new Week2("星期三");
private String name;
private Week2(String name){
this.name = name;
}
public String getName() {
return name;
}
}
package com.heima.enumeration;
/**
* Code by pureqh on 2021-03-28
*/
public abstract class Week3 {
public static final Week3 MON = new Week3("星期一"){
public void show(){
System.out.println("星期一");
}
};
public static final Week3 TUE = new Week3("星期二"){
public void show(){
System.out.println("星期二");
}
};
public static final Week3 WED = new Week3("星期三"){
public void show(){
System.out.println("星期三");
}
};
private String name;
private Week3(String name){
this.name = name;
}
public String getName() {
return name;
}
public abstract void show();
}
/**
* Code by pureqh on 2021-03-28
*/
public abstract class Week3 {
public static final Week3 MON = new Week3("星期一"){
public void show(){
System.out.println("星期一");
}
};
public static final Week3 TUE = new Week3("星期二"){
public void show(){
System.out.println("星期二");
}
};
public static final Week3 WED = new Week3("星期三"){
public void show(){
System.out.println("星期三");
}
};
private String name;
private Week3(String name){
this.name = name;
}
public String getName() {
return name;
}
public abstract void show();
}
package com.heima.enumeration;
/**
* Code by pureqh on 2021-03-28
*/
public class Demo1_Enum {
public static void main(String[] args) {
//demo1();
//demo2();
Week3 mon = Week3.MON;
mon.show();
}
private static void demo2() {
Week2 mon = Week2.MON;
System.out.println(mon.getName());
}
private static void demo1() {
Week mon = Week.MON;
Week tue = Week.TUE;
Week wed = Week.WED;
}
}
/**
* Code by pureqh on 2021-03-28
*/
public class Demo1_Enum {
public static void main(String[] args) {
//demo1();
//demo2();
Week3 mon = Week3.MON;
mon.show();
}
private static void demo2() {
Week2 mon = Week2.MON;
System.out.println(mon.getName());
}
private static void demo1() {
Week mon = Week.MON;
Week tue = Week.TUE;
Week wed = Week.WED;
}
}
通过enum实现枚举类
package com.heima.enumeration2;
/**
* Code by pureqh on 2021-03-28
*/
public class Demo1_Enum {
public static void main(String[] args) {
//demo1();
//demo2();
Week3 mon = Week3.MON;
mon.show();
}
private static void demo2() {
Week2 mon = Week2.MON;
System.out.println(mon.getName());
}
private static void demo1() {
Week mon = Week.MON;
System.out.println(mon);
}
}
/**
* Code by pureqh on 2021-03-28
*/
public class Demo1_Enum {
public static void main(String[] args) {
//demo1();
//demo2();
Week3 mon = Week3.MON;
mon.show();
}
private static void demo2() {
Week2 mon = Week2.MON;
System.out.println(mon.getName());
}
private static void demo1() {
Week mon = Week.MON;
System.out.println(mon);
}
}
package com.heima.enumeration2;
/**
* Code by pureqh on 2021-03-28
*/
public enum Week {
MON,TUE,WED;
}
/**
* Code by pureqh on 2021-03-28
*/
public enum Week {
MON,TUE,WED;
}
package com.heima.enumeration2;
/**
* Code by pureqh on 2021-03-30
*/
public enum Week3 {
MON("星期一") {
public void show(){
System.out.println("星期一");
}
},TUE("星期二"){
public void show(){
System.out.println("星期二");
}
},WED("星期三"){
public void show(){
System.out.println("星期三");
}
};
private String name;
private Week3(String name){
this.name = name;
}
public String getName() {
return name;
}
public abstract void show();
}
/**
* Code by pureqh on 2021-03-30
*/
public enum Week3 {
MON("星期一") {
public void show(){
System.out.println("星期一");
}
},TUE("星期二"){
public void show(){
System.out.println("星期二");
}
},WED("星期三"){
public void show(){
System.out.println("星期三");
}
};
private String name;
private Week3(String name){
this.name = name;
}
public String getName() {
return name;
}
public abstract void show();
}
枚举类的常见方法
package com.heima.enumeration2;
import org.omg.Messaging.SyncScopeHelper;
/**
* Code by pureqh on 2021-03-30
*/
public class Demo2_Enum {
public static void main(String[] args) {
//demo();
/* Week2 mon = Week2.valueOf(Week2.class,"MON"); //通过字节码对象获取枚举项
System.out.println(mon);*/
Week2[] arr = Week2.values();
for (Week2 week2 :arr
) {
System.out.println(week2);
}
}
private static void demo() {
Week2 mon = Week2.MON;
Week2 tue = Week2.TUE;
Week2 wed = Week2.WED;
System.out.println(mon.ordinal()); //枚举项都是有编号的
System.out.println(tue.ordinal());
System.out.println(mon.compareTo(wed));
System.out.println(mon.compareTo(tue));
System.out.println(mon.name()); //获取实例名称
System.out.println(mon.toString()); //调用重写后的tostring方法
}
}
import org.omg.Messaging.SyncScopeHelper;
/**
* Code by pureqh on 2021-03-30
*/
public class Demo2_Enum {
public static void main(String[] args) {
//demo();
/* Week2 mon = Week2.valueOf(Week2.class,"MON"); //通过字节码对象获取枚举项
System.out.println(mon);*/
Week2[] arr = Week2.values();
for (Week2 week2 :arr
) {
System.out.println(week2);
}
}
private static void demo() {
Week2 mon = Week2.MON;
Week2 tue = Week2.TUE;
Week2 wed = Week2.WED;
System.out.println(mon.ordinal()); //枚举项都是有编号的
System.out.println(tue.ordinal());
System.out.println(mon.compareTo(wed));
System.out.println(mon.compareTo(tue));
System.out.println(mon.name()); //获取实例名称
System.out.println(mon.toString()); //调用重写后的tostring方法
}
}