傳入類名,通過反射,將泛型例項化
阿新 • • 發佈:2019-02-13
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");
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");