集册 Java实例教程 通过反射获取字段的通用类型

通过反射获取字段的通用类型

欢马劈雪     最近更新时间:2020-01-02 10:19:05

416
通过反射获取字段的通用类型

import java.lang.reflect.Field;

import java.util.List;


public class FieldSpy<T> {
/**来自 
 N  o w  J a v a . c o m**/

    public boolean[][] b = { { false, false }, { true, true } };

    public String name = "Alice";

    public List<Integer> list;

    public T val;


    public static void main(String... args) {

        try {

            Class<?> c = Class.forName(args[0]);

            Field f = c.getField(args[1]);/** nowjava.com - 时  代  Java 提 供 **/

            System.out.format("Type: %s%n", f.getType());

            System.out.format("GenericType: %s%n", f.getGenericType());


            // production code should handle these exceptions more gracefully

        } catch (ClassNotFoundException x) {

            x.printStackTrace();

        } catch (NoSuchFieldException x) {

            x.printStackTrace();

        }

    }

}


展开阅读全文