java.lang.reflect.Field 中的 toGenericString 和 toString 有什么区别

What is the difference between toGenericString and toString in java.lang.reflect.Field

package com.sample;

import java.lang.reflect.Field;

class Demo {
    int i;
}

public class DifferenceGenericStringAndToString {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        Class c = Demo.class;
        Field[] fields = c.getDeclaredFields();
        for(Field field : fields) {
            System.out.println(field.toGenericString());
            System.out.println(field.toString());
        }
    }
}

输出为:-

int com.sample.Demo.i

int com.sample.Demo.i

谁能告诉我这些方法有什么区别吗?

嗯,来自 javadoc:

toGenericString() Returns a string describing this Field, including its generic type.

toString() Returns a string describing this Field.

所以如果你的 Field 没有泛型类型,也没有区别。

有关泛型的更多信息,请查看此处:https://docs.oracle.com/javase/tutorial/java/generics/

真正的答案在这里:如有疑问,请阅读 javadoc:

Returns a string describing this Field, including its generic type. The format is the access modifiers for the field, if any, followed by the generic field type, followed by a space, followed by the fully-qualified name of the class declaring the field, followed by a period, followed by the name of the field.

The modifiers are placed in canonical order as specified by "The Java Language Specification". This is public, protected or private first, and then other modifiers in the following order: static, final, transient, volatile.

而对于 toString() 来说:

Returns a string describing this Field. The format is the access modifiers for the field, if any, followed by the field type, followed by a space, followed by the fully-qualified name of the class declaring the field, followed by a period, followed by the name of the field.

正如 namejavadoc 泄露的那样:这与 generics 有关.因此,您可能希望将测试代码更改为,使用泛型。