我正在编写一个程序来显示类中的方法及其访问修饰符、返回类型和参数。
这是我的代码
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();
}
}
测试.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[] parameters = meth.getTypeParameters();
行得到一个空白的 TypeVariable
数组/p>
有人能给我指出正确的方向吗?
谢谢。
最佳答案
getTypeParameters()
返回 type parameters 的数组在方法定义中使用。它不返回参数类型数组。考虑这种方法:
public <T> void foo(int bar);
getTypeParameters()
将返回一个包含 T
的数组(即 TypeVariable
,名称为 T
,边界为 {对象.class }
).
getParameterTypes()
但是,将返回一个包含 int.class
的数组。
注意:如果您的参数类型包含类型参数,那么您需要使用 getGenericParameterTypes()
.
关于java - getTypeParameters 返回一个空的 TypeVariable 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5403207/