[英]Is there any way to instantiate a Class<C<A,B>> object in java?
I'm trying to use Hibernate and TypedQuery in java. 我正在尝试在Java中使用Hibernate和TypedQuery。
The method I'm trying to call has a signature of 我尝试调用的方法的签名为
<T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass)
I want to call it like bellow but with null replaced by a real instance. 我想像波纹管那样称呼它,但将null替换为真实实例。
Class<Tuple2<Date,String>> cls=null;
List<Tuple2<Date,String>> books=em.createQuery("select new io.vavr.Tuple2(date,title) from Book where publicationdate > '2008-01-01'",cls).getResultList();
the above code compiles but obviously chrashes with a null pointer exception. 上面的代码可以编译,但显然会因空指针异常而崩溃。
If my understanding of erasure is correct this would work as long as I get an instance of the Class object as all generic type information would be lost at runtime anyway. 如果我对擦除的理解是正确的,那么只要我得到Class对象的实例,这将一直有效,因为所有泛型类型信息无论如何都会在运行时丢失。
Is there any way I can get an instance of Class that i can assign to the variable cls so that this code will work? 有什么方法可以获取可以分配给变量cls的Class实例,以便此代码起作用?
Based on @Thomas comments on the first post I came upp with the following. 基于@Thomas在第一篇文章中的评论,我提供了以下内容。
While it dies not seems to be a way to instantiate such a Class object a relativly readable solution can be achived with subclassing. 尽管它死似乎不是实例化此类Class对象的方法,但是可以通过子类实现相对可读的解决方案。
In the class where the code resides add outside any function 在代码所在的类中,在任何函数之外添加
public static class DateStringPair extends Pair<Date,String>{
public DateStringPair(Date d,String s){super(d,s);}
}
And then the call becomes 然后电话变成
List<DateStringPair> books=em.createQuery(
"select new com.example.ConnectionAndQueryTest$DateStringPair(publicationDate,title) from Book where publicationDate > '2008-01-01'"
,DateStringPair.class).getResultList( );
this have the limitation that the Pair class must not be final. 这有一个限制,那就是Pair类一定不能是final。
While not as flexible as full generics support in the query readability of the query can be maintained without that much fuss. 虽然不如完整的泛型支持那么灵活,但可以保持查询的可读性,而不必大惊小怪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.