我最近一直在看java中的反射,我想出了一个简单的例子
反射.java
import java.lang.reflect.*;
public class Reflection{
}
public static void main(String args[])
{
try {
Class cls = Class.forName("Method");
Method methlist[]
= cls.getDeclaredMethods();
for (int i = 0; i < methlist.length;
i++) {
Method m = methlist[i];
System.out.println("name
= " + m.getName());
System.out.println("decl class = " +
m.getDeclaringClass());
Class pvec[] = m.getParameterTypes();
for (int j = 0; j < pvec.length; j++)
System.out.println("
param #" + j + " " + pvec[j]);
Class evec[] = m.getExceptionTypes();
for (int j = 0; j < evec.length; j++)
System.out.println("exc #" + j
+ " " + evec[j]);
System.out.println("return type = " +
m.getReturnType());
System.out.println("-----");
}
}
catch (Throwable e) {
System.err.println(e);
}
}
}
方法.java
public class Method {
private int f1(
Object p, int x) throws NullPointerException
{
if (p == null)
throw new NullPointerException();
return x;
}
从上面的示例中,我能够返回所有Method.java
看起来像这样的信息
name = f1
decl class = class Method
param #0 class java.lang.Object
param #1 int
exc #0 class java.lang.NullPointerException
return type = int
-----
name = main
decl class = class method1
param #0 class [Ljava.lang.String;
return type = void
-----
但我的问题是,有没有办法用类似Method.java
的Reflection.java
东西进行测试
int x = cls.getMethod("f1", Object = anObject, Integer.TYPE = 2 )
System.out.println(x);
并且控制台应该打印出 2 因为 f1 被传递了一个对象?