面试常问编译->加载阶段,应用常问运行->加载阶段
re.properties(src包下)
classfullpath=Reflection.Cat
//method=hi
method=cry
Cat
package Reflection;
/**
* @author whlie(true){learn}
*/
public class Cat {
private String name="招财猫";
public int age=1;
public Cat(){}
public Cat(String name){
this.name=name;
}
public void hi(){
System.out.println("我是"+name);
}
public void cry(){
System.out.println("你是"+name);
}
}
Ocp
package Reflection;
import java.io.FileInputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Properties;
/**
* @author whlie(true){learn}
*/
public class Ocp {
public static void main(String[] args) throws Exception {
//使用该方法读取配置文件
Properties p = new Properties();
p.load(new FileInputStream("src\\re.properties"));
String classfullpath = p.get("classfullpath").toString();
String method = p.get("method").toString();
//反射机制
//(1)加载类,返回Class类型的对象cls
Class cls = Class.forName(classfullpath);
//(2)通过cls得到你加载的类com.wzg.Cat的对象实例
Object o = cls.newInstance();
System.out.println("o的运行类型"+o.getClass());
//(3)通过cls得到你加载的类com.wzg.Cat的method"hi"的方法对象
// 即在反射中可以视方法为对象
Method method1 = cls.getMethod(method);
//(4)通过method1调用方法即通过方法对象来实现调用方法
// 传统:对象.方法() 反射:方法.invoke(对象)
method1.invoke(o);
//(5)获取指定类的成员变量
// 传统:对象.成员变量 反射:成员变量对象.get(对象)
Field age = cls.getField("age");
System.out.println("你的年龄是:"+age.get(o));
//(6)获取指定类的构造器,如果()里为空则为无参构造器,int类的class对象
Constructor constructor = cls.getConstructor(String.class);
System.out.println(constructor);
}
}
反射与传统方法相比,调优
package Reflection;
import java.lang.reflect.Method;
/**
* @author whlie(true){learn}
*/
public class Tuning {
public static void main(String[] args) throws Exception {
t1();
t2();
t3();
}
//传统方法
public static void t1(){
Cat cat = new Cat();
long start =System.currentTimeMillis();
for (int i = 0; i < 900000000; i++) {
cat.hi();
}
long end = System.currentTimeMillis();
System.out.println("传统方法耗时:"+(end-start));
}
//反射(未调优)
public static void t2() throws Exception {
Class cls = Class.forName("Reflection.Cat");
Object o = cls.newInstance();
Method hi = cls.getMethod("hi");
long start =System.currentTimeMillis();
for (int i = 0; i < 900000000; i++) {
hi.invoke(o);
}
long end = System.currentTimeMillis();
System.out.println("反射(未调优)耗时:"+(end-start));
}
//反射(调优后)
public static void t3() throws Exception {
Class cls = Class.forName("Reflection.Cat");
Object o = cls.newInstance();
Method hi = cls.getMethod("hi");
//在反射调用方法时取消检查
hi.setAccessible(true);
long start =System.currentTimeMillis();
for (int i = 0; i < 900000000; i++) {
hi.invoke(o);
}
long end = System.currentTimeMillis();
System.out.println("反射(调优后)耗时:"+(end-start));
}
}