java 反射访问方法

来源:互联网 发布:网络流行语2016我好饿 编辑:程序博客网 时间:2024/06/08 10:21

1.待测试类

public class Method {

static void staticMethod() {
System.out.println("执行静态的空方法staticMethd");
}

public int publicMethod(int i) {
System.out.println("执行publicMethod方法");
return i * 100;
}

protected int protectedMethod(String s, int i) {
System.out.println("执行protectedMethod方法");
return Integer.valueOf(s)  + i;
}

private String privateMethod(String ...strings ) {
System.out.println("执行privateMethod方法");
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < strings.length; i++) {
stringBuffer.append(strings[i]);
}

return stringBuffer.toString();
}

}


2.测试类


import java.lang.reflect.InvocationTargetException;


public class TestMethod {


public static void main(String[] args) {
Method method = new Method();
Class example = method.getClass();

// 获取所有方法存放在数组中
java.lang.reflect.Method[] declaredMethods = example.getDeclaredMethods();
for (int i = 0; i < declaredMethods.length; i++) {
java.lang.reflect.Method meth = declaredMethods[i];
System.out.println("名称为:" + meth.getName());
System.out.println("是否允许带有变参: " + meth.isVarArgs());
System.out.println("入口参数类型依次为:");

// 获取所有参数类型
Class[] parameterTypes = meth.getParameterTypes();
for (int j = 0; j < parameterTypes.length; j++) {
System.out.println(parameterTypes[j] + "\t");
}

//获取方法返回值的类型
System.out.println("返回值类型为:" + meth.getReturnType());

// 获取方法可能抛出的所有异常类型
System.out.println("可能抛出的异常类型有:");
Class[] exceptionTypes = meth.getExceptionTypes();
for (int j = 0; j < exceptionTypes.length; j++) {
System.out.println(exceptionTypes[j] + " \t");
}

boolean isTurn = true;
while(isTurn) {
isTurn = false;
try {
if ("staticMethod".equals(meth.getName())) {
meth.invoke(method);
} else if ("publicMethod".equals(meth.getName())) {
System.out.println("返回值为:" + meth.invoke(method, 40));
} else if ("protectedMethod".equals(meth.getName())) {
System.out.println("返回值为:" + meth.invoke(method, "10", 5));
} else if ("privateMethod".equals(meth.getName())) {
Object[] parameters = new Object[] {new String[]{"abc", "123", "def456"} };

System.out.println("返回值为" + meth.invoke(method, parameters));
}


} catch (IllegalAccessException e) {
// e.printStackTrace();
System.out.println("执行方法时抛出异常,执行setAccessible方法");
meth.setAccessible(true);
isTurn = true;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}


}





}

}

}

0 0
原创粉丝点击