You'll have to create an entirely separate constructor for when the Class
object is being passed in directly. You can't infer it again the way you're trying to.
Instantiate Java anonymous inner class with generic using Class in variable
-
04-08-2022 - |
Domanda
Is it possible in Java 7 to instantiate an anonymous inner class with a generic type using a Class
object that I have in hand?
Here's the simplified version of the generic class I'm trying to instantiate:
abstract class DomainBuilder<E> {
private final Class<E> entityClass
public DomainBuilder() {
this.entityClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
...
}
Creating an anonymous inner class when I specify the class I want to build at compile time works fine:
DomainBuilder builder = new DomainBuilder<MyDomainClass>() {}
I'd like to be able to make it so that I can use a Class
variable that I've determined at run-time like this, but haven't figured out how to yet:
Class clazz = MyDomainClass.class
...
DomainBuilder builder = new DomainBuilder<clazz>() {}
I've also tried creating methods along these lines without luck:
Class clazz = MyDomainClass.class
DomainBuilder builder = builderFor(clazz)
public static DomainBuilder<T> builderFor(Class<T> t) {
return new DomainBuilder<T>(entityManager){}
}
Is something like this possible?
Soluzione
Altri suggerimenti
I'd like to be able to make it so that I can use a Class variable that I've determined at run-time like this, but haven't figured out how to yet:
Class clazz = MyDomainClass.class ... DomainBuilder builder = new DomainBuilder<clazz>() {}
we can't actually do it this way. Because by doing so, we are not defining a class Type
in the diagonal <>
, rather passing an object claszz
of type Class
.