Java operates generics through reflection

Generic and class classes

public class ObjectFactory {
    public static Object getInstance(String clsName) {
        try {
            // 创建指定类对应的Class对象
            Class cls = Class.forName(clsName);
            // 返回使用该Class对象创建的实例
            return cls.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

//After obtaining the instance, you need to cast date d = (date) objectfactory getInstance("java.util.Date");

JFrame f = (JFrame)ObjectFactory . getInstance("java.util.Date");

public class ObjectFactory2 {
    public static <T> T getInstance(Class<T> cls) {
        try {
            return cls.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        // 获取实例后无须类型转换
        Date d = CrazyitObjectFactory2.getInstance(Date.class);
        JFrame f = CrazyitObjectFactory2.getInstance(JFrame.class);
    }
}

//Use the newinstance method of array to create an array object array = array newInstance(String.class,10);

public static Object newInstance(Class componentType,int... dimensions)

public static
T[] newInstance(Class

componentType,int length)

public class CrazyitArray {
    // 对Array的newInstance方法进行包装
    @SuppressWarnings("unchecked")
    public static <T> T[] newInstance(Class<T> componentType,int length) {
        return (T[]) Array.newInstance(componentType,length); 
    }

    public static void main(String[] args) {
        // 使用 CrazyitArray 的 newInstance()创建一维数组
        String[] arr = CrazyitArray.newInstance(String.class,10);
        // 使用 CrazyitArray 的 newInstance()创建二维数组
        // 在这种情况下,只要设置数组元素的类型是int[]即可
        int[][] intArr = CrazyitArray.newInstance(int[].class,5);
        arr[5] = "C语言中文网Java教程";
        // intArr是二维数组,初始化该数组的第二个数组元素
        // 二维数组的元素必须是一维数组
        intArr[1] = new int[]{ 23,12 };
        System.out.println(arr[5]);
        System.out.println(intArr[1][1]);
    }
}

Use reflection to get generic information

//Get the type class of member variable f a = f.getType();

//Get the generic type of member variable F, type gType = f.getgenerictype();

public class GenericTest {
    private Map<String,Integer> score;

    public static void main(String[] args) throws Exception {
        Class<GenericTest> clazz = GenericTest.class;
        Field f = clazz.getDeclaredField("score");
        // 直接使用getType()取出类型只对普通类型的成员变量有效
        Class<?> a = f.getType();
        // 下面将看到仅输出java.util.Map
        System.out.println("score 的类型是:" + a);
        // 获得成员变量f的泛型类型
        Type gType = f.getGenericType();
        // 如果 gType 类型是 ParameterizedType对象
        if (gType instanceof ParameterizedType) {
            // 强制类型转换
            ParameterizedType pType = (ParameterizedType) gType;
            // 获取原始类型
            Type rType = pType.getRawType();
            System.out.println("原始类型是:" + rType);
            // 取得泛型类型的泛型参数
            Type[] tArgs = pType.getActualTypeArguments();
            System.out.println("泛型信息是:");
            for (int i = 0; i < tArgs.length; i++) {
                System.out.println("第" + i + "个泛型类型是:" + tArgs[i]);
            }
        } else {
            System.out.println("获取泛型类型出错!");
        }
    }
}

The type of score is: Interface Java util. The original type of map is: Interface Java util. The map generic information is: the 0th generic type is: class java Lang.string the first generic type is: class java lang.Integer

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>