package test;
public class Person{
private String name;
private int age;
private double salary;
public int abc;
private void a(String a) {
a="A";
System.out.println("this is "+a);
}
public void b(String a,int b) {
a="b";b=3;
System.out.println("this is "+a+",and it's="+b);
}
protected void c() {
System.out.println("this is c");
}
void d(String a,String b) {
System.out.println("this is "+a+b);
}
}
package test;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
public class GetPerson {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
//加载类
Class<?> clazz=Class.forName("test.Person");
//实例化对象
Object o=clazz.getConstructor().newInstance();
System.out.println(o);
//参数数组
Field[] fields=clazz.getDeclaredFields();
//方法数组
Method[] methods=clazz.getDeclaredMethods();
//遍历参数
for (Field field : fields) {
//强制读取私有变量
field.setAccessible(true);
System.out.println("变量===="+field);
}
//便利方法
for (Method method : methods) {
//强制读取私有方法
method.setAccessible(true);
System.out.println("方法=========="+method);
//遍历方法的参数
Class<?>[] paramtypes=method.getParameterTypes();
//使用不带参数的方法
if(paramtypes.length==0) {method.invoke(o);continue;}
Arrays.asList(paramtypes).forEach(System.out::println);
}
//使用d方法
Class[] patype=new Class[2];
patype[0]=String.class;
patype[1]=String.class;
Method m=clazz.getDeclaredMethod("d", patype);
m.invoke(o, "AAAA","BBBBB");
}
}