反射基础
2018-06-11 本文已影响0人
行动的侏儒
反射
反射能在运行时获取任意一个类的所有属性和方法,前提是他能获取到类的Class对象
/*反射的基本使用*/
public class ReflectDemo {
private String privateFiled = "private filed qaq";
public String publicFiled = "public filed qaq";
boolean BoolFiled = true;
private void privateMethod() {
System.out.println("private method");
}
public void publicMethod(String str) {
System.out.println("public method " +str);
}
public void publicMethodWithoutParam() {
System.out.println("public method without param");
}
public ReflectDemo() {}
public ReflectDemo(String str){};
private ReflectDemo(String str1,String str2){};
}
public class TestReflect {
public static void main(String[] args) {
try {
Class clazz = Class.forName("com.reda.reflect.ReflectDemo");
//调用构造方法公有构造方法
Constructor ctor1 = clazz.getConstructor();
//带参数共有构造方法
Constructor ctor2 = clazz.getConstructor(String.class);
//私有构造方法
Constructor ctor3 = clazz.getDeclaredConstructor(String.class,String.class);
ctor3.setAccessible(true);
Object obj = ctor1.newInstance();
Object obj2 = ctor2.newInstance("qaq");
Object obj3 = ctor3.newInstance("1","2");
//调用公有域
Field field1 = clazz.getField("publicFiled");
System.out.println(field1.get(obj));
//调用包可见域
Field field2 = clazz.getDeclaredField("BoolFiled");
System.out.println(field2.getBoolean(obj2));
//调用私有域
Field field3 = clazz.getDeclaredField("privateFiled");
field3.setAccessible(true);
System.out.println(field3.get(obj2));
//调用方法public方法
Method method1 = clazz.getMethod("publicMethodWithoutParam");
method1.invoke(obj);
//调用带参数的public方法
Method method2 = clazz.getMethod("publicMethod",String.class);
method2.invoke(obj3,"qaq");
//调用私有方法
Method privateMethod = clazz.getDeclaredMethod("privateMethod");
privateMethod.setAccessible(true);
privateMethod.invoke(obj3);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}