我正在编写一个程序,它显示类中的方法以及它的访问修饰符,返回类型和参数.
这是我的代码
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();
}
}
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
每一件事情是工作的罚款,但我不明白为什么我得到的空白阵列TypeVariable的行TypeVariable[] parameters = meth.getTypeParameters();
有人可以指出我正确的方向吗?
谢谢.
Joa*_*uer 11
getTypeParameters()返回方法定义中使用的类型参数数组.它并没有返回参数类型的数组.考虑这种方法:
public <T> void foo(int bar);
Run Code Online (Sandbox Code Playgroud)
getTypeParameters()将返回一个包含的数组T(即TypeVariable带有名称T和边界的数组{ Object.class }).
getParameterTypes()但是,会返回一个包含的数组int.class.
注意:如果参数类型包含类型参数,那么您需要使用getGenericParameterTypes().
| 归档时间: |
|
| 查看次数: |
4317 次 |
| 最近记录: |