两种反射构造方法的区别
- Construcotr.newInstance()
- Class.forName("pathName").getConstructor().newInstance();
- Class.newInstance()
- Teat.class.newInstance() or
Class.forName("pathName").newInstance();
- Teat.class.newInstance() or
- 区别
-
Class.newInstance() 只能反射无参构造方法,只能反射公开(public)的构造方法
Object getFanShe1 = ReflactUtil.invokeMethod(new MainActivity(), "getFanShe");
Object getFanShe2 = ReflactUtil.invokeMethod2(MainActivity.class, "getFanShe");
Object getFanShe3 = ReflactUtil.invokeMethod3("com.example.fewwind.keymap.MainActivity", "getFanShe");
-
`public class ReflactUtil {
//任何一个类都是Class 的实例对象,这个实例对象有三种表达方式
// 第一种表达方式: 已知该类的对象,通过getClass方法,第一个参数表示 已知的对象
public static Object invokeMethod(Object obj, String methodName) {
Class<? extends Object> clazz = obj.getClass();
try {
Method method = clazz.getDeclaredMethod(methodName);
method.setAccessible(true);// 获取私有方法必须加上
return method.invoke(obj);
} catch (Exception e) {
e.printStackTrace();
Logger.e("反射异常--"+e.toString());
}
return "反射错误";
}
// 第二种表达方式。--》任何一个类都有一个隐含的静态成员变量
public static Object invokeMethod2(Class<?> cla, String methodName) {
try {
Method method = cla.getDeclaredMethod(methodName);
return method.invoke(cla.newInstance());
} catch (Exception e) {
e.printStackTrace();
Logger.e("反射异常--"+e.toString());
}
return "反射错误";
}
// 第3种表达方式。--》 Class.forName()
public static Object invokeMethod3(String claName, String methodName) {
Class clazz = null;
try {
clazz = Class.forName(claName);
Method method = clazz.getDeclaredMethod(methodName);
return method.invoke(clazz.newInstance());
} catch (Exception e) {
e.printStackTrace();
Logger.e("反射异常--"+e.toString());
}
return "反射错误";
}
public class ClassDemo1 {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
//Foo的实例对象如何表示
Foo foo1=new Foo();//foo1就表示出来了
//Foo这个类 也是一个实例对象,Class类的实例对象如何表示
//任何一个类都是Class类的实例对象,这个实例对象有3中表示方式
/*第一种表示方式--》实际在告诉我们任何一个类都有一个隐含的静态成员变量*/
Class c1=Foo.class;
/*第二种表达方式:已知该类的对象,通过getClass方法*/
Class c2=foo1.getClass();
/*官网:c1/c2表示了Foo类的类类型(class type)
* 类也是对象,是class类的实例对象
* 这个对象我们成为该类的类类型
* */
/*不管c1 or c2都代表了Foo类的类类型,一个类只可能是Class类的一个对象*/
System.out.println(c1==c2);//true
//第三种表达方式
Class c3=null;
c3=Class.forName("ShuiTian.NaiLuo.Reflect.Foo");
System.out.println(c3);
/*我们完全可以通过类的类类型创建该类的对象
* 通过c1 or c2 or c3创建父的实例
*
* */
Foo foo=(Foo)c1.newInstance();//使用newInstance需要有无参数的构造方法
}
}
网友评论