用户类:
public class UserEntity {
private static final String TAG = UserEntity.class.getSimpleName();
private final int money = 1;
//无参方法
public int method1() {
Log.d(TAG, "method1: 无参");
return money;
}
//单个参数
public void method2(int a) {
Log.d(TAG, "method1: 单个参数");
}
//多个参数
public void method3(String a, int b) {
Log.d(TAG, "method1: 多个参数");
}
}
测试类:
/**
* 反射调用方法获取返回值
*/
public class Reflection {
public static void main(String[] args) throws Exception {
//获取Class对象
//1、通过类的.class属性获取
Class<UserEntity> userClass = UserEntity.class;
//2、通过类的完整路径获取,这个方法由于不能确定传入的路径是否正确,这个方法会抛ClassNotFoundException
Class<?> userClass1 = Class.forName("com.lf.entity.UserEntity");
//3、通过new一个实例,然后通过实例的getClass()方法获取
UserEntity s = new UserEntity();
Class<? extends UserEntity> userClass2 = s.getClass();
UserEntity userEntity = (UserEntity) userClass.newInstance();
//第一种方法
int i = userEntity.method1();
//第二种方法,(无参的示例),获取类中方法名为method1的方法,getMethod第一个参数为方法名,第二个参数为方法的参数类型数组
Method classMethod1 = userClass.getMethod("method1");
Object object = classMethod1.invoke(userEntity);
//如果方法method1是私有的private方法,按照上面的方法去调用则会产生异常NoSuchMethodException,这时必须改变其访问属性
//method.setAccessible(true);//私有的方法通过发射可以修改其访问权限
//第二种方法,(单个参数的示例)
Method classMethod2 = userClass.getMethod("method2", int.class);
classMethod2.invoke(userEntity, 100);
//第二种方法,(多个参数的示例)
Method classMethod3 = userClass.getMethod("method3", String.class, int.class);
classMethod3.invoke(userEntity, "张三", 200);
}
}
网友评论