Java讓泛型例項化的方法
阿新 • • 發佈:2020-07-14
泛型物件可以例項化嗎?
不可以,T t=new T()是不可以的,編譯器會報錯。由於泛型擦除,編譯器在編譯時無法確定泛型所對應的真實型別
解決方法
使用反射新建例項
Type superclass = getClass().getGenericSuperclass(); ParameterizedType parameterizedType = null; if (superclass instanceof ParameterizedType) { parameterizedType = (ParameterizedType) superclass; Type[] typeArray = parameterizedType.getActualTypeArguments(); if (typeArray != null && typeArray.length > 0) { clazz = (Class<T>) typeArray[0]; } }
執行結果
控制檯輸出
完整程式碼
package com.learn.genericinstance; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; public class GenericInstanceLearn { public static void main(String[] args) throws InstantiationException,IllegalAccessException { UserDao userDao = new UserDao(); System.out.println(userDao.toString()); } } class Dao<T> { public Class<T> clazz; public T user; public Dao() throws IllegalAccessException,InstantiationException { Type superclass = getClass().getGenericSuperclass(); ParameterizedType parameterizedType = null; if (superclass instanceof ParameterizedType) { parameterizedType = (ParameterizedType) superclass; Type[] typeArray = parameterizedType.getActualTypeArguments(); if (typeArray != null && typeArray.length > 0) { clazz = (Class<T>) typeArray[0]; user= clazz.newInstance(); } } } @Override public String toString() { return "Dao{" + "user=" + user.toString() + '}'; } } class UserDao extends Dao<User> { public UserDao() throws IllegalAccessException,InstantiationException { } @Override public String toString() { return super.toString(); } } class User { String name; public User() { this.name = "default name"; } @Override public String toString() { return "User{" + "name='" + name + '\'' + '}'; } }
以上就是Java讓泛型例項化的方法的詳細內容,更多關於Java泛型例項化的資料請關注我們其它相關文章!