1. 程式人生 > >傳入類名,通過反射,將泛型例項化

傳入類名,通過反射,將泛型例項化

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");