}
利用安全管理器及反射,可以在不修改源码的基础上访问私有成员,为测试带来了极大的方便。尤其是在编译期间,该方法可以顺利地通过编译。但同时该方法也有一些缺点。第一个是性能问题,用于字段和方法接入时反射要远慢于直接代码。第二个是权限问题,有些涉及 Java 安全的程序代码并没有修改安全管理器的权限,此时本方法失效。
常见问题:
java反射调用静态方法
Class c;
c = Class.forName("class name");
Method m = c.getMethod("method name", new Class[] { int.class, int.class, int.class, int.class });
m.invoke(c, new Object[] { 1, 2, 3, 4 });
利用反射取得泛型信息
一、传统通过反射取得函数的参数和返回值
import java.lang.reflect.Method;
public class Foo {
public static void main(String[] args) throws Exception {
Method[] methods = Foo.class.getDeclaredMethods();
for (Method method : methods) {
Class[] paramTypeList = method.getParameterTypes();
Class returnType = method.getReturnType();
System.out.println(returnType);
for (Class clazz : paramTypeList) {
System.out.println(clazz);
}
System.out.println();
}
}
public static String test1(String str) {
return null;
}
public static Integer test2(String str, Integer i) {
return null;
}
}
二、在有泛型的时候,取得参数和返回值的集合类的泛型信息
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.List;
public class Foo {
public static void main(String[] args) throws Exception {
Method[] methods = Foo.class.getDeclaredMethods();
for (Method method : methods) {
System.out.println(" returnType: ");
Type returnType = method.getGenericReturnType();
if (returnType instanceof ParameterizedType) {
Type[] types = ((ParameterizedType) returnType).getActualTypeArguments();
for (Type type : types) {
System.out.println(type);
}
}
System.out.println(" paramTypeType: ");
Type[] paramTypeList = method.getGenericParameterTypes();
for (Type paramType : paramTypeList) {
if (paramType instanceof ParameterizedType) {
Type[] types = ((ParameterizedType) paramType).getActualTypeArguments();
for (Type type : types) {
System.out.println(type);
}
}
}
&nb