我正在写一个程序,它显示了一个Class中的方法以及它的访问修饰符,返回类型和参数。getTypeParameters返回一个null TypeVariable数组
这里是我的代码
import java.lang.reflect.*;
class RefTest1{
public static void main(String[] args) throws Exception{
Test obj = new Test();
Class<?> c = obj.getClass();
System.out.printf("%n%s fields :-%n", obj.getClass());
Field[] fields = c.getDeclaredFields();
for(Field f : fields){
f.setAccessible(true);
int m = f.getModifiers();
if(Modifier.isStatic(m)){
System.out.printf("%s is static variable and its value is %s%n", f.getName(), f.get(obj));
}else if(Modifier.isPublic(m)){
System.out.printf("%s is public variable and its value is %s%n", f.getName(), f.get(obj));
}else if(Modifier.isPrivate(m)){
System.out.printf("%s is private variable and its value is %s%n", f.getName(), f.get(obj));
}else if(Modifier.isProtected(m)){
System.out.printf("%s is protected variable and its value is %s%n", f.getName(), f.get(obj));
}
}
System.out.printf("%n%s methods :-%n", obj.getClass());
Method[] methods = c.getDeclaredMethods();
for(Method meth : methods){
int m = meth.getModifiers();
meth.setAccessible(true);
if(Modifier.isStatic(m)){
System.out.printf("%s is static method%n", meth.getName());
}else if(Modifier.isPublic(m)){
System.out.printf("%s is public method%n", meth.getName());
}else if(Modifier.isPrivate(m)){
System.out.printf("%s is private method%n", meth.getName());
}else if(Modifier.isProtected(m)){
System.out.printf("%s is protected method%n", meth.getName());
}
System.out.printf("%nReturn Type :- %s%n", meth.getReturnType());
System.out.printf("%nParameters:-%n");
TypeVariable[] parameters = meth.getTypeParameters();
for(TypeVariable param : parameters){
System.out.printf("%s", param.getName());
}
}
System.out.println();
}
}
Test.java
class Test{
private int x;
public double y;
protected String z;
static long a;
public Test(){
x = 10;
y = 20;
z = "Hello";
a = 15L;
}
public void Print(String a){
a = a;
System.out.println("Executing Print function.");
}
private void hidden(double b){
b = b;
//private function
}
}
,任何东西都工作正常,但我不明白为什么我在得到线的TypeVariable
空白阵列TypeVariable[] parameters = meth.getTypeParameters();
有人能指出我正确的方向吗?
谢谢。
我打过电话getParameterTypes但它仍然给了我一个空白阵列。请参阅编辑,我认为我的代码中有错误。 – Searock 2011-03-23 10:01:01
@Searock:将您的更改合并到您的原始代码后,它会为我打印参数类型。请注意,不要在类型之后打印换行符,但是,因此可能很容易错过。 – 2011-03-23 10:03:44
我真的很抱歉,这是我的错。有一个换行符的问题,因为我没有注意到参数类型。非常感谢您的快速响应。 – Searock 2011-03-23 10:07:14