在父类的构造方法中,获取泛型的具体类型
import javalangreflectParameterizedType;
import javalangreflectType;
import comopensymphonyxwork2ModelDriven;
/
工具类直接返回ModelDriven的对象
/
public class ModelBaseAction<T> extends BaseAction implements ModelDriven<T> {
protected T model;
/
通过反射,获取泛型的具体类型并实例化这个类型
/
public ModelBaseAction() {
// 获取反射的类型
javalangreflectType cls = supergetClass()getGenericSuperclass();
if (cls instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) cls;
// 获取所有放到泛型里面的类型
Type[] tps = ptgetActualTypeArguments();
Systemerrprintln(tps[0]getTypeName());
try {
// 实例化这个泛型所代表的类对象
model = (T) ClassforName(tps[0]getTypeName())newInstance();
} catch (Exception e) {
throw new RuntimeException("没有默认构造方法", e);
}
}
}
@Override
public final T getModel() {
return model;
}
}
泛型的类型是无法在运行时通过反射取得的,泛型类型在编译成字节码的时候已经被虚拟机给去掉了,只是起到提示编译器进行类型检查的作用
用这种方法你试一试:父类:import javalangreflectParameterizedType;
public class Parent<T {
public Parent() {
ParameterizedType type = (ParameterizedType)thisgetClass()getGenericSuperclass();
Systemoutprintln("type==" + type);
Systemoutprintln("entityClass==" + typegetActualTypeArguments()[0]);
Systemoutprintln("getOwnerType==" + typegetOwnerType());
Systemoutprintln("getRawType==" + typegetRawType());}}子类:public class Child<T extends Parent<String {
我可以给你demo,你可以参考
接口你可以自己写package comshoppingb2bdaoimpl;
import javaioSerializable;
import javalangreflectField;
import javautilCollection;
import javautilList;
import javautilMap;
import javaxannotationResource;
import javaxpersistenceTable;
import orgapachelog4jLogger;
import orghibernateHibernate;
import orghibernateQuery;
import orghibernateSQLQuery;
import orghibernateSession;
import orghibernateSessionFactory;
import orghibernatetransformTransformers;
import orgspringframeworkbeansfactoryannotationAutowired;
import orgspringframeworkstereotypeRepository;
import comshoppingb2bdaoISuperDao;
@Repository("superDao")
public class SuperDaoImpl implements ISuperDao{
@Resource
private SessionFactory hibernateSessionFactory;
public SessionFactory getHibernateSessionFactory() {
return hibernateSessionFactory;
}
public void setHibernateSessionFactory(SessionFactory hibernateSessionFactory) {
thishibernateSessionFactory = hibernateSessionFactory;
}
private Logger logger = LoggergetLogger(thisgetClass());
private Session getCurrentSession() {
return thishibernateSessionFactorygetCurrentSession();
}
@Override
public <T> T get(Class<T> clazz, Serializable id) {
return (T)thisgetCurrentSession()get(clazz, id);
}
@Override
public <T> T getSql(String sql, Map<String, Object> params, Class<T> po) {
SQLQuery q = thisgetCurrentSession()createSQLQuery(sql);
/
say:
从数据库查出来的数据类型给po,如果要自定义,那么需要扩展addScalar
默认情况:数据库字段类型是什么类型,返回的po也是什么类型。移植性不好
可扩展
/
if(po != null){
qsetResultTransformer(TransformersaliasToBean(po));
}else{
qsetResultTransformer(TransformersALIAS_TO_ENTITY_MAP);
}
if(params != null && !paramsisEmpty()){
for (String k : paramskeySet()) {
Object v = paramsget(k);
if(v != null){
if(v instanceof Object[]){
qsetParameterList(k, (Object[])v);
}else if(v instanceof Collection<>){
qsetParameterList(k, (Collection<>)v);
}else{
qsetParameter(k, v);
};
}
}
}
List<T> list = qlist();
return list == null || listisEmpty() null:listget(0);
}
@Override
public Serializable save(Object entity) {
return thisgetCurrentSession()save(entity);
}
@Override
public boolean update(Object entity) {
boolean result = false;
try {
thisgetCurrentSession()update(entity);
result = true;
} catch (Exception e) {
result = false;
}
return result;
}
@Override
public boolean updateSql(String sql,Map<String, Object> params) {
SQLQuery q = thisgetCurrentSession()createSQLQuery(sql);
if(params != null && !paramsisEmpty()){
for (String k : paramskeySet()) {
Object v = paramsget(k);
if(v != null){
if(v instanceof Object[]){
qsetParameterList(k, (Object[])v);
}else if(v instanceof Collection<>){
qsetParameterList(k, (Collection<>)v);
}else{
qsetParameter(k, v);
};
}
}
}
return qexecuteUpdate() == 0 false :true;
}
@Override
public boolean delete(Object entity) {
boolean result = false;
try {
thisgetCurrentSession()delete(entity);
result = true;
} catch (Exception e) {
result = false;
}
return result;
}
@Override
public <T> boolean deleteSql(Class<T> clazz,Serializable id) {
boolean result = false;
try {
Table table = (Table)clazzgetAnnotation(Tableclass);
if(table != null){
String tableName = tablename();
thisgetCurrentSession()
createSQLQuery("delete from :tableName where id = :id")
setParameter("tableName", tableName)
setParameter("id", id)
executeUpdate();
}
result = true;
} catch (Exception e) {
result = false;
}
return result;
}
@Override
public <T> List<T> queryList(String sql, Map<String, Object> params, Class<T> po) {
SQLQuery q = thisgetCurrentSession()createSQLQuery(sql);
/
say:
从数据库查出来的数据类型给po,如果要自定义,那么需要扩展addScalar
默认情况:数据库字段类型是什么类型,返回的po也是什么类型。移植性不好
可扩展
/
if(po != null){
qsetResultTransformer(TransformersaliasToBean(po));
}else{
qsetResultTransformer(TransformersALIAS_TO_ENTITY_MAP);
}
if(params != null && !paramsisEmpty()){
for (String k : paramskeySet()) {
Object v = paramsget(k);
if(v != null){
if(v instanceof Object[]){
qsetParameterList(k, (Object[])v);
}else if(v instanceof Collection<>){
qsetParameterList(k, (Collection<>)v);
}else{
qsetParameter(k, v);
}
}
}
}
List<T> list = qlist();
return list == null || listisEmpty() null:list;
}
@Override
public <T> List<T> queryList(String sql, Map<String, Object> params, int firstResult, int maxResults, Class<T> po) {
SQLQuery query = thisgetCurrentSession()createSQLQuery(sql);
/
say:
从数据库查出来的数据类型给po,如果要自定义数据类型,那么需要扩展addScalar
默认情况:数据库字段类型是什么类型,返回的po也是什么类型。移植性不好
可扩展
/
if(po != null){
querysetResultTransformer(TransformersaliasToBean(po))setFirstResult(firstResult)setMaxResults(maxResults);
}else{
querysetResultTransformer(TransformersALIAS_TO_ENTITY_MAP)setFirstResult(firstResult)setMaxResults(maxResults);
}
//thisaddScalarsToString(query, po)setFirstResult(firstResult)setMaxResults(maxResults);//test
if(params != null && !paramsisEmpty()){
for (String k : paramskeySet()) {
Object v = paramsget(k);
if(v != null){
if(v instanceof Object[]){
querysetParameterList(k, (Object[])v);
}else if(v instanceof Collection<>){
querysetParameterList(k, (Collection<>)v);
}else{
querysetParameter(k, v);
}
}
}
}
List<T> list = querylist();
return list == null || listisEmpty() null:list;
}
@Override
public <T> Serializable queryCount(String sql, Map<String, Object> params) {
Query query = thisgetCurrentSession()createSQLQuery(sql);
if(params != null && !paramsisEmpty()){
for (String k : paramskeySet()) {
Object v = paramsget(k);
if(v != null){
if(v instanceof Object[]){
querysetParameterList(k, (Object[])v);
}else if(v instanceof Collection<>){
querysetParameterList(k, (Collection<>)v);
}else{
querysetParameter(k, v);
}
}
}
}
return IntegerparseInt(queryuniqueResult()toString());
}
/
扩展
默认将class的属性类型转换为hibernate所对应的的类型<br/>
如果严格的话请使用TransformersaliasToBean(Tclass)<br/>
对应表如下:
未实现
@param query
@param cls
@return
/
private <T> Query addScalarsToCustom(SQLQuery query,Class<T> cls){
Field[] fields = clsgetDeclaredFields();
for(Field item:fields){
////Systemoutprintln(itemgetName() + ":" + itemgetGenericType());
//该接口需要判断,返回的属性类型,然后转换为hibernate语法
//Systemoutprintln(itemgetName() + ":" + itemgetGenericType());
//该接口需要判断,返回的属性类型,然后转换为hibernate语法
if("class javamathBigInteger"equals(itemgetGenericType()toString())){
//Systemoutprintln(clsgetName() +":"+itemgetName() + " ||==int");
}else if("class javalangString"equals(itemgetGenericType()toString())){
//Systemoutprintln(clsgetName() +":"+itemgetName() + " ||==String");
}else if("class javamathBigDecimal"equals(itemgetGenericType()toString())){
//Systemoutprintln(clsgetName() +":"+itemgetName() + " ||==String");
}else{
//Systemoutprintln(clsgetName() +":"+itemgetName() + " ||==未匹配类型");
}
}
return null;
}
}
以上就是关于Java问题,泛型问题,通过实例对象获取T的类型如:public class Base<T>{}全部的内容,包括:Java问题,泛型问题,通过实例对象获取T的类型如:public class Base<T>{}、java泛型该怎么深继承 amp;怎么获得数组的class对象、怎样使用泛型实现Hibernate查询返回对象等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)