import android.app.Activity;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectTest {
public static void main(String[] args){
try {
Class<Person> activityClass = (Class<Person>) Class.forName("com.example.myapplication.Person");
System.out.println("---------------------构造器相关 Start ------------------");
Constructor<Person>[] constructors = (Constructor<Person>[]) activityClass.getConstructors();
System.out.println("------------- class.getConstructors()获取所有构造器-----------------");
for (Constructor c : constructors) {
System.out.println(c);
}
Person person = activityClass.newInstance();
person.setAge(18);
System.out.println("通过class创建对象 class.newInstance() age : " +person.getAge());
System.out.println("获取指定构造器 class.getDeclaredConstructor ---------");
Constructor constructor = activityClass.getDeclaredConstructor(int.class,String.class);
Person person1 = (Person) constructor.newInstance(19,"xiaoming");
System.out.println("通过构造器创建对象 constructor.newInstance age : " +person1.getAge());
System.out.println("---------------------构造器相关 End------------------");
Method[] methods = activityClass.getMethods();
System.out.println("------------- class.getMethods() 获取所有方法 ,包括父类方法但是不包括私有方法-----------------");
for (Method method : methods){
System.out.println(method.getName());
}
Method method1 = activityClass.getMethod("setName",String.class);
System.out.println("—————————————获取指定方法并打印 class.getMethod method.getName() : " + method1.getName());
method1.invoke(person,"zhangsan");
System.out.println("----------------利用invoke方法调用对象方法赋值 method.invoke name : " + person.getName());
Method[] methodss = activityClass.getDeclaredMethods();
System.out.println("------------打印所有方法 包括私有共有方法 class.getDeclaredMethods ------------");
for(Method method: methodss){
System.out.println(""+method.getName());
}
System.out.println("------------执行私有方法 method.setAccessible method.invoke ------------");
Method privateMethod = activityClass.getDeclaredMethod("privateMethod");
privateMethod.setAccessible(true);
privateMethod.invoke(person);
System.out.println("------------获取所有属性字段,包括私有属性 class.getDeclaredFields------");
Field[] fields = activityClass.getDeclaredFields();
for (Field f: fields){
System.out.println(" " + f.getName());
}
Field field = activityClass.getDeclaredField("name");
field.setAccessible(true);
field.set(person,"xiaosan");
System.out.println("----------设置指定对象的值 field.set name : " + person.getName());
Field field1 = activityClass.getDeclaredField("age");
field1.setAccessible(true);
System.out.println("----------获取私有属性的值 field.setAccessible field.get age " + field1.get(person));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Android 反射笔记
最新推荐文章于 2024-07-09 02:22:53 发布
该代码示例展示了如何使用Java的反射API来操作类的构造器、方法和属性字段。首先,它获取`Person`类的所有构造器并创建实例。接着,通过反射调用公共方法和私有方法,以及设置和获取私有属性的值。
1167

被折叠的 条评论
为什么被折叠?



