传入类名,通过反射,将泛型实例化

来源:互联网 发布:螃蟹 知乎 编辑:程序博客网 时间:2024/06/05 09:33
package com.example.shopsystem;


import java.util.ArrayList;


public class HibernateTest {
    public<T> void test(String className) {
        try {
            T t = (T) Class.forName(className).newInstance();
            System.out.println(t.toString());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }


    @Override
    public String toString() {
        return "123";
    }


    public static void main(final String[] args) throws Exception {
        HibernateTest hibernateTest = new HibernateTest();
        System.out.println(hibernateTest.toString());
        hibernateTest.test("com.example.shopsystem.HibernateTest");
原创粉丝点击