这种泛型反射需求如何实现?
interface IBaseDao <T extends Serializable, ID extends Serializable>{} @Component("baseDao") public class BaseDao<T extends Serializable, ID extends Serializable> extends HibernateDaoSupport implements IBaseDao<T,ID>{ private Class<T> entityClazz;
当new BaseDao<User,Integer>的时候
如何通过反射在BaseDao的构造中获得User的类
然后可以setter进entityClazz中
现在碰到的问题就是这个反射不会写!
倘若我不实现IBaseDao接口,又是否能实现?
百度了,但是根据样本,发现不能出效果,不知为何?
高手们是否能提供一个解决方案?谢谢了
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这样啊!感谢回复指教!
可以实现的,给你一个代码片段
/*
* Copyright @ 2006-2010 by The Jxva Framework Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jxva.dao;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author The Jxva Framework Foundation
* @since 1.0
* @version 2009-03-30 15:25:07 by Jxva
*/
public abstract class GenericDao<T> extends BaseDao{
private static final Map<Class<?>,Class<?>> cache=new HashMap<Class<?>,Class<?>>();
protected final Class<T> entityClass;
@SuppressWarnings("unchecked")
public GenericDao(){
super();
Class<?> cls=getClass();
Class<?> result=cache.get(cls);
if(result!=null){
entityClass=(Class<T>)result;
}else{
entityClass=(Class<T>)getEntityClass(cls);
cache.put(cls,entityClass);
}
}
private Class<?> getEntityClass(Class<?> cls){
Type type=cls.getGenericSuperclass();
if(type.toString().lastIndexOf('>')>-1){
return (Class<?>)((ParameterizedType)type).getActualTypeArguments()[0];
}else{
throw new DAOException("com.jxva.dao.GenericDao's subclass must be generic class");
}
}
public Class<T> getEntityClass(){
return this.entityClass;
}
public T get(Object pkey) {
return dao.get(entityClass,pkey);
}
public int delete(Object pkey){
return dao.delete(entityClass,pkey);
}
public List<T> findAll(){
return dao.find(entityClass);
}
public List<T> findPageBean(PageBean pageBean){
return dao.findPageBean(entityClass, pageBean);
}
public List<T> findPaginated(int index,int size){
return dao.findPaginated(entityClass, index, size);
}
}
泛型的信息在编译时就被编译器给擦除了,无法获取实例化BaseDao时T的具体类型