[英]Method generic return java class
I am building generic methods for queries to the database with Hibernate, the following method consults the information of an entity by primary key. 我正在使用Hibernate构建用于查询数据库的通用方法,以下方法通过主键查询实体的信息。
@PersistenceContext(unitName = "UnitPers")
private EntityManager entity;
public Object findByPk(Class clazz, Object pk) throws Exception {
Object obj = null;
try {
obj = entity().find(clazz, pk);
} catch (Exception e) {
throw e;
}
return obj;
}
This method works correctly, but I do not want to make a cast (object to myTypeEntity) when making the call. 此方法正常工作,但是在进行调用时,我不想进行强制类型转换(对象为myTypeEntity)。
private myTypeEntity entity;
entity = (myTypeEntity) findByPk(myTypeEntity.class, new Bigdecimal("1"));
//GET and SET Methods
I want to avoid doing the cast when calling this method, bearing in mind that it is one of the purposes of the generic, but I have not managed to do it, any ideas? 我想避免在调用此方法时进行强制转换,请记住这是泛型的目的之一,但是我没有设法做到这一点,有什么想法吗? or what I intend to do is not possible.
或我打算做的事是不可能的。
You can use generics instead of using Object: 您可以使用泛型而不是对象:
public <T> T findByPk(Class<T> clazz, Object pk) throws Exception {
T obj = null;
try {
obj = entity().find(clazz, pk);
} catch (Exception e) {
throw e;
}
return obj;
}
And then it should work without doing the cast 然后它应该不做演员就可以工作
private myTypeEntity entity;
entity = findByPk(myTypeEntity.class, new Bigdecimal("1"));
By introducing a generic type variable on the method level you can define what type should be returned, this can be seen in @cpr4t3s' answer. 通过在方法级别引入通用类型变量,您可以定义应返回的类型,这可以在@ cpr4t3s的答案中看到。
You can also shorten his snippet to the following: 您还可以将他的代码段缩短为以下内容:
public <T> T findByPk(Class<T> clazz, Object pk) throws Exception {
return entity().find(clazz, pk);
}
Because: 因为:
catch
-block catch
-block中抛出异常 obj
-variable obj
-variable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.