public class TestReflect {
public static void main(String[] args) {
// getConstructor();
// getMothed();
// getFiled();
getArrayFieldMethod();
}
/**
* 通过反射获取参数是数组的方法
*/
private static void getArrayFieldMethod() {
try {
//获取参数是数组的方法
Class person4 = Class.forName("com.fanshe1.Person");
Method method =person4.getMethod("printArray", String [].class);
Object obj = person4.newInstance();
method.invoke(obj,(Object) new String[]{"aaa","bbb","ccc"});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 通过反射获取属性
*/
private static void getFiled() {
try {
Class person3 = Class.forName("com.fanshe1.Person");
System.out.println("111");
//获取公开字段
// Field[] fields = person3.getFields();
// for(Field field:fields){
// System.out.println(field);
// }
//获取私有字段
Field[] declaredFields = person3.getDeclaredFields();
for(Field field : declaredFields){
System.out.println(field);
}
Field field = person3.getDeclaredField("name");
field.setAccessible(true);
Object obj = person3.newInstance();
field.set(obj, "小六");
String str = (String)field.get(obj);
System.out.println(str);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 通过反射获取方法(参数 返回值)
*/
private static void getMothed(){
try {
//获取类的对象
Class person2 = Class.forName("com.fanshe1.Person");
//获取所有继承链中公共的方法
// Method[] methods = person2.getMethods();
// for(Method method:methods)
// {
// System.out.println(method);
// }
//获取所有该类中公共和私有的方法
// Method[] declaredMethods = person2.getDeclaredMethods();
// for(Method method:declaredMethods){
// System.out.println(method);
// }
//获取无参无返回值
Method method = person2.getMethod("showInfo", null);
Object obj = person2.newInstance();
method.invoke(obj, null);
//获取带参数无返回值
Method method1 = person2.getMethod("showInfo", String.class);
method1.invoke(obj, "北京");
//获取无参有返回值
Method method2 = person2.getMethod("getInfo", null);
String str = (String)method2.invoke(obj, null);
System.out.println(str);
//获取私有方法
Method method3 = person2.getDeclaredMethod("data", null);
method3.setAccessible(true);
method3.invoke(obj, null);
//获取静态方法
Method method4 = person2.getMethod("staticmethod", null);
// method4.setAccessible(true);
method4.invoke(null, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 通过反射获取构造方法
*/
private static void getConstructor() {
// TODO Auto-generated method stub
try {
Class person1 = Class.forName("com.fanshe1.Person");
// Constructor[] constructors = person1.getConstructors();
// for(Constructor constructor:constructors)
// {
// System.out.println(constructor);
// }
Constructor con1= person1.getConstructor(String.class,int.class,String.class);
Object obj1 = con1.newInstance("aa",18,"男");
System.out.println(obj1.toString());
Object obj2 = person1.newInstance();
System.out.println(obj2);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}