您的位置:首页 > 编程语言 > Java开发

Java反射一篇讲完

2018-03-12 13:59 141 查看
想用完成反射得一步一步的来,需要Class、实例、还有想要调用的函数地址,传入的参数
获取Class
TestClass testClass = new TestClass();
Class<?> cls = testClass.getClass();

try {
cls = Class.forName("com.example.zth.seven.thread.TestClass");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}从Class里得到实例化的对象

TestClass two = null;
try {
two = TestClass.class.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
遍历变量
Field[] fields = cls.getFields();
for (Field field : fields) {
field.getName();
field.getType().getCanonicalName();
field.getGenericType().toString();
}
改变特定变量的值
try {
Field idCarNumber = cls.getDeclaredField("sum");
idCarNumber.setInt(testClass, 33);

} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
遍历函数,因为函数有参数、返回值、注解、异常,代码就很多了
//遍历函数,因为函数有很多属性,代码有点多
Method[] declaredMethods = cls.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
declaredMethod.getName(); //获得单独的方法名
//获得完整的方法信息(包括修饰符、返回值、路径、名称、参数、抛出值)
declaredMethod.toGenericString();

int modifiers = declaredMethod.getModifiers(); //获得修饰符

declaredMethod.getReturnType(); //获得返回值
declaredMethod.getGenericReturnType();//获得完整信息的返回值

Class<?>[] parameterTypes = declaredMethod.getParameterTypes(); //获得参数类型
Type[] genericParameterTypes = declaredMethod.getGenericParameterTypes();
for (int i = 0; i < parameterTypes.length; i++) {
Class<?> parameterType = parameterTypes[i];
Type genericParameterType = genericParameterTypes[i];
}

Class<?>[] exceptionTypes = declaredMethod.getExceptionTypes(); //获得异常名称
Type[] genericExceptionTypes = declaredMethod.getGenericExceptionTypes();
for (int i = 0; i < exceptionTypes.length; i++) {
Class<?> exceptionType = exceptionTypes[i];
Type genericExceptionType = genericExceptionTypes[i];
}

Annotation[] annotations = declaredMethod.getAnnotations(); //获得注解
for (Annotation annotation : annotations) {
Annotation annotation1 = annotation;
annotation.annotationType();
}
}
反射的使用 try {
for (Method declaredMethod : declaredMethods) {
String methodName = declaredMethod.getName(); //获取方法名

if (methodName.equals("addSum")) {
TestClass testClass1 = new TestClass();
try {
Object invokeResult = declaredMethod.invoke(two, 22);
} catch (InvocationTargetException e) { //处理被调用方法可能抛出的异常
}
}

}

} catch (IllegalAccessException e) {
e.printStackTrace();
}
注意事项
反射的函数必须是public,还有就是传入数据,需要转object Method declaredMethod = cls.getDeclaredMethod("printVarArgs", String[].class);
String[] varArgs = {"shixin", "zhang"};
declaredMethod.invoke(object, (Object) varArgs);
还有就是泛型擦除,就是你函数有泛型参数或者返回值 public void getSum(T t){

}那对于使用反射时,你必须当他是getSum(Object t),除非你<T extends View>,那你当他是getSum(View t)

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: