如何打印类型 getter

How to print a type of getter

我有如下代码:

public static void main(String[] args) throws Exception {
    printGettersSetters(PodmiotSzukajQueryFormSet.class);
}

public static void printGettersSetters(Class aClass) {
    Method[] methods = aClass.getMethods();

    for (Method method: methods) {
        if (isGetter(method)) {
            System.out.println("getter: " + method);    
        }
    }
}

public static boolean isGetter(Method method) {
    if (!method.getName().startsWith("getSomething")) {
        return false;
    }
    if (method.getParameterTypes().length != 0) return false;
    if (void.class.equals(method.getReturnType())) return false;
    return true;
}

输出:

getter: public package.package.Class package.package.Class.getSomething()

如何获得 getter 的类型,在此示例中:"Class" 但在其他示例中 "String" 、 "int" 等

--编辑 有可能与 .getModifiers() 但它 returns int。我怎样才能 return String?

想一想您正在寻找对象 java.lang.reflect.Method

的方法 getReturnType()

public Class getReturnType()

Returns a Class object that represents the formal return type of the method represented by this Method object.

Returns:the return type for the method this object represents

在您的 for 循环中执行此操作:

for (Method method : methods) {
  if (isGetter(method)) {
    String type = String.valueOf(method.getReturnType());
    System.out.println("getter: " + method + ". Return type: " + type);
  }
}