I got the following class:
public class Repository<T> extends ExternalRepository<Wrapper<T>>
{
public Repository(Class<Wrapper<T>> type, DB db)
{
super(type, db);
}
}
But I have no idea how to call the construtor since
new Repository(Wrapper<SomeClass>.class, dbInstance)
does not work. So what can I do? I can change the Repository class if necessary.
You can't get the class instance for Wrapper<SomeClass> directly using .class literal. It is not allowed. You can only use it with raw type - Wrapper.class, or unbounded wildcard types - Wrapper<?>.class.
To get what you want, you've to use some type-casting here:
new Repository<SomeClass>((Class<Wrapper<SomeClass>>)(Class<?>)Wrapper.class,
dbInstance)
This first cast a Class<Wrapper> to a Class<?>, which is an unbounded wildcard reference. And then that reference can be type-casted to Class<Wrapper<SomeClass>>.
Also, don't forget to give the type argument while creating an instance of your generic class.
Here's what you need:
new Repository(Wrapper.class, dbInstance);
There's only one class descriptor for each generic class, including Wrapper.
Related
public class Module<T> {
#SuppressWarnings("unchecked")
public <T> T module(Class<T> clazz) {
return clazz.cast(this);
}
}
This is the base class of my module and I want to initialize it to TestModule by calling the module method above.
TestingModule testingModule = new Module().module(TestingModule.class);
However, the return type of
new Module().module(TestingModule.class)
is Object instead of TestingModule. Is there any idea that I can directly initialize it without using any casting or changing the method to static?
There are a few problems. The one most directly linked to the type mismatch error is here:
TestingModule testingModule = new Module().module(TestingModule.class);
new Module() is using Module without any type argument. When you use a raw type like this, you lose all generic information in the expression. You can fix it simply by adding a type argument:
TestingModule testingModule = new Module<String>().module(TestingModule.class);
In the above code, I've added <String> to the constructor call, which resolves the problem. But String is as strange a type argument as it can get in this case, which leads to the following side note.
The declaration public <T> T module(Class<T> clazz) adds a type variable T that hides the class-level type variable of the same name. If this method is not made generic by accident, please use a different name for this variable, and use it. Otherwise, this method doesn't need to be generic.
Following snippet is self-explanatory enough. You can see that type information is not erased, but mapper doesn't get the type information. My guess is that jackson doesn't allow this, right ? If I pass TypeReference directly, it is deserialized properly.
public class AgentReq<T> extends TypeReference<AgentResponse<T>> {...}
mapper.readValue(reader, new AgentReq<Map<String, Set<Whatever>>>());
It also doesn't work if I do this :
public class AgentReq<T> {
public TypeReference<AgentResponse<T>> getTypeRef() {
return new TypeReference<AgentResponse<T>>() {};
}
}
mapper.readValue(reader, new AgentReq<Map<String, Set<Whatever>>>()).getTypeRef();
I'm using version 2.1.5.
EDIT: For future reference, do not underestimate the TypeReference constructor when resolving problems. There you can see directly whether it was able to retrieve type information. Btw the answer is NO, you can't extend TypeReference and expect it to work, you can't even override its getType() method and supply it with type information resolved from your class, because all you can get is getClass().getGenericSuperClass() ... You can't do getClass().getGenericClass()
You need to understand how a TypeReference works. For that we go into the source code
protected TypeReference()
{
Type superClass = getClass().getGenericSuperclass();
if (superClass instanceof Class<?>) { // sanity check, should never happen
throw new IllegalArgumentException("Internal error: TypeReference constructed without actual type information");
}
...
_type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
}
The Class#getGenericSuperclass() javadoc states
Returns the Type representing the direct superclass of the entity
(class, interface, primitive type or void) represented by this Class.
If the superclass is a parameterized type, the Type object returned
must accurately reflect the actual type parameters used in the source
code.
In other words, if we could do new TypeReference() (we can't, it's abstract), it would return the Class instance for the class Object. However, with anonymous classes (which extend from the type)
new TypeReference<String>(){}
the direct superclass of the instance created is the parameterized type TypeReference and according to the javadoc we should get a Type instance that accurately reflect the actual type parameters used in the source code:
TypeReference<String>
from which you can then get the parameterized type with getActualTypeArguments()[0]), returning String.
Let's take an example to visualize using anonymous class and using a sub-class
public class Subclass<T> extends TypeReference<AgentResponse<T>>{
public Subclass() {
System.out.println(getClass().getGenericSuperclass());
System.out.println(((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
}
}
Running
new Subclass<String>();
prints
com.fasterxml.jackson.core.type.TypeReference<Test.AgentResponse<T>>
Test.AgentResponse<T>
which fits the javadoc rules. Test.AgentResponse<T> is the actual parameterized type in the source code. Now, if instead, we had
new Subclass<String>(){}; // anonymous inner class
we get the result
Test.Subclass<java.lang.String>
class java.lang.String
which also fits the bill. The inner class now extends directly from Subclass which is parameterized with the argument String in the source code.
You will notice that, with the Subclass anonymous inner class, we've lost information about the AgentResponse generic type. This is unavoidable.
Note that
reader = new StringReader("{\"element\":{\"map-element\":[{\"name\":\"soto\", \"value\": 123}]}}");
obj = mapper.readValue(reader, new AgentReq<Map<String, Set<Whatever>>>());
will compile and run, but the type AgentReq<Map<String, Set<Whatever>>> will have been lost. Jackson will use default type to serializes the JSON. The element will be deserialized as an AgentResponse, while map-element will be deserialized as a Map and the JSON array as an ArrayList.
Following snippet is self-explanatory enough. You can see that type information is not erased, but mapper doesn't get the type information. My guess is that jackson doesn't allow this, right ? If I pass TypeReference directly, it is deserialized properly.
public class AgentReq<T> extends TypeReference<AgentResponse<T>> {...}
mapper.readValue(reader, new AgentReq<Map<String, Set<Whatever>>>());
It also doesn't work if I do this :
public class AgentReq<T> {
public TypeReference<AgentResponse<T>> getTypeRef() {
return new TypeReference<AgentResponse<T>>() {};
}
}
mapper.readValue(reader, new AgentReq<Map<String, Set<Whatever>>>()).getTypeRef();
I'm using version 2.1.5.
EDIT: For future reference, do not underestimate the TypeReference constructor when resolving problems. There you can see directly whether it was able to retrieve type information. Btw the answer is NO, you can't extend TypeReference and expect it to work, you can't even override its getType() method and supply it with type information resolved from your class, because all you can get is getClass().getGenericSuperClass() ... You can't do getClass().getGenericClass()
You need to understand how a TypeReference works. For that we go into the source code
protected TypeReference()
{
Type superClass = getClass().getGenericSuperclass();
if (superClass instanceof Class<?>) { // sanity check, should never happen
throw new IllegalArgumentException("Internal error: TypeReference constructed without actual type information");
}
...
_type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
}
The Class#getGenericSuperclass() javadoc states
Returns the Type representing the direct superclass of the entity
(class, interface, primitive type or void) represented by this Class.
If the superclass is a parameterized type, the Type object returned
must accurately reflect the actual type parameters used in the source
code.
In other words, if we could do new TypeReference() (we can't, it's abstract), it would return the Class instance for the class Object. However, with anonymous classes (which extend from the type)
new TypeReference<String>(){}
the direct superclass of the instance created is the parameterized type TypeReference and according to the javadoc we should get a Type instance that accurately reflect the actual type parameters used in the source code:
TypeReference<String>
from which you can then get the parameterized type with getActualTypeArguments()[0]), returning String.
Let's take an example to visualize using anonymous class and using a sub-class
public class Subclass<T> extends TypeReference<AgentResponse<T>>{
public Subclass() {
System.out.println(getClass().getGenericSuperclass());
System.out.println(((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
}
}
Running
new Subclass<String>();
prints
com.fasterxml.jackson.core.type.TypeReference<Test.AgentResponse<T>>
Test.AgentResponse<T>
which fits the javadoc rules. Test.AgentResponse<T> is the actual parameterized type in the source code. Now, if instead, we had
new Subclass<String>(){}; // anonymous inner class
we get the result
Test.Subclass<java.lang.String>
class java.lang.String
which also fits the bill. The inner class now extends directly from Subclass which is parameterized with the argument String in the source code.
You will notice that, with the Subclass anonymous inner class, we've lost information about the AgentResponse generic type. This is unavoidable.
Note that
reader = new StringReader("{\"element\":{\"map-element\":[{\"name\":\"soto\", \"value\": 123}]}}");
obj = mapper.readValue(reader, new AgentReq<Map<String, Set<Whatever>>>());
will compile and run, but the type AgentReq<Map<String, Set<Whatever>>> will have been lost. Jackson will use default type to serializes the JSON. The element will be deserialized as an AgentResponse, while map-element will be deserialized as a Map and the JSON array as an ArrayList.
I have some legacy Java code that defines a generic payload variable somewhere outside of my control (i.e. I can not change its type):
// Java code
Wrapper<? extends SomeBaseType> payload = ...
I receive such a payload value as a method parameter in my code and want to pass it on to a Scala case class (to use as message with an actor system), but do not get the definitions right such that I do not get at least a compiler warning.
// still Java code
ScalaMessage msg = new ScalaMessage(payload);
This gives a compiler warning "Type safety: contructor... belongs to raw type..."
The Scala case class is defined as:
// Scala code
case class ScalaMessage[T <: SomeBaseType](payload: Wrapper[T])
How can I define the case class such that the code compiles cleanly? (sadly, changing the code of the Java Wrapper class or the type of the payload parameter is not an option)
Updated to clarify the origin of the payload parameter
Added For comparison, in Java I can define a parameter just in the same way as the payload variable is defined:
// Java code
void doSomethingWith(Wrapper<? extends SomeBaseType> payload) {}
and call it accordingly
// Java code
doSomethingWith(payload)
But I can't instantiate e.g. a Wrapper object directly without getting a "raw type" warning. Here, I need to use a static helper method:
static <T> Wrapper<T> of(T value) {
return new Wrapper<T>(value);
}
and use this static helper to instantiate a Wrapper object:
// Java code
MyDerivedType value = ... // constructed elsewhere, actual type is not known!
Wrapper<? extends SomeBaseType> payload = Wrapper.of(value);
Solution
I can add a similar helper method to a Scala companion object:
// Scala code
object ScalaMessageHelper {
def apply[T <: SomeBaseType](payload: Wrapper[T]) =
new ScalaMessage(payload)
}
object ScalaMessageHelper2 {
def apply[T <: SomeBaseType](payload: Wrapper[T]) =
ScalaMessage(payload) // uses implicit apply() method of case class
}
and use this from Java to instantiate the ScalaMessage class w/o problems:
// Java code
ScalaMessage msg = ScalaMessageHelper.apply(payload);
Unless someone comes up with a more elegant solution, I will extract this as an answer...
Thank you!
I think the problem is that in Java if you do the following:
ScalaMessage msg = new ScalaMessage(payload);
Then you are instantiating ScalaMessage using its raw type. Or in other words, you use ScalaMessage as a non generic type (when Java introduced generics, they kept the ability to treat a generic class as a non-generic one, mostly for backward compatibility).
You should simply specify the type parameters when instantiating ScalaMessage:
// (here T = MyDerivedType, where MyDerivedType must extend SomeBaseType
ScalaMessage<MyDerivedType> msg = new ScalaMessage<>(payload);
UPDATE: After seeing your comment, I actually tried it in a dummy project, and I actually get an error:
[error] C:\Code\sandbox\src\main\java\bla\Test.java:8: cannot find symbol
[error] symbol : constructor ScalaMessage(bla.Wrapper<capture#64 of ? extends bla.SomeBaseType>)
[error] location: class test.ScalaMessage<bla.SomeBaseType>
[error] ScalaMessage<SomeBaseType> msg = new ScalaMessage<SomeBaseType>(payload);
It seems like a mismatch between java generics (that we can emulate through exitsentials in scala ) and scala generics. You can fix this by just dropping the type parameter in ScalaMessage and using existentials instead:
case class ScalaMessage(payload: Wrapper[_ <: SomeBaseType])
and then instantiate it in java like this:
new ScalaMessage(payload)
This works. However, now ScalaMessage is not generic anymore, which might be a problem if you want use it with more refined paylods (say a Wrapper<? extends MyDerivedType>).
To fix this, let's do yet another small change to ScalaMessage:
case class ScalaMessage[T<:SomeBaseType](payload: Wrapper[_ <: T])
And then in java:
ScalaMessage<SomeBaseType> msg = new ScalaMessage<SomeBaseType>(payload);
Problem solved :)
What you are experiencing is the fact that Java Generics are poorly implemented. You can't correctly implement covariance and contravariance in Java and you have to use wildcards.
case class ScalaMessage[T <: SomeBaseType](payload: Wrapper[T])
If you provide a Wrapper[T], this will work correctly and you'll create an instance of a ScalaMessage[T]
What you would like to do is to be able to create a ScalaMessage[T] from a Wrapper[K] where K<:T is unknown. However, this is possible only if
Wrapper[K]<:Wrapper[T] for K<:T
This is exactly the definition of variance. Since generics in Java are invariant, the operation is illegal. The only solution that you have is to change the signature of the constructor
class ScalaMessage[T](wrapper:Wrapper[_<:T])
If however the Wrapper was implemented correctly in Scala using type variance
class Wrapper[+T]
class ScalaMessage[+T](wrapper:Wrapper[T])
object ScalaMessage {
class A
class B extends A
val myVal:Wrapper[_<:A] = new Wrapper[B]()
val message:ScalaMessage[A] = new ScalaMessage[A](myVal)
}
Everything will compile smoothly and elegantly :)
I'm using Hibernate validator and trying to create a little util class:
public class DataRecordValidator<T> {
public void validate(Class<T> clazz, T validateMe) {
ClassValidator<T> validator = new ClassValidator<T>(clazz);
InvalidValue[] errors = validator.getInvalidValues(validateMe);
[...]
}
}
Question is, why do I need to supply the Class<T> clazz parameter when executing new ClassValidator<T>(clazz)? Why can't you specify:
T as in ClassValidator<T>(T)?
validateMe.getClass() as in ClassValidator<T>(validateMe.getClass())
I get errors when I try to do both options.
Edit: I understand why #1 doesn't work. But I don't get why #2 doesn't work. I currently get this error with #2:
cannot find symbol
symbol : constructor ClassValidator(java.lang.Class<capture#279 of ? extends java.lang.Object>)
location: class org.hibernate.validator.ClassValidator<T>
Note: Hibernate API method is (here)
Because T is not a value - it's just a hint for the compiler. The JVM has no clue of the T. You can use generics only as a type for the purposes of type checking at compile time.
If the validate method is yours, then you can safely skip the Class atribute.
public void validate(T validateMe) {
ClassValidator<T> validator =
new ClassValidator<T>((Class<T>) validateMe.getClass());
...
}
But the ClassValidator constructor requires a Class argument.
Using an unsafe cast is not preferred, but in this case it is actually safe if you don't have something like this:
class A {..}
class B extends A {..}
new DataRecordValidator<A>.validate(new B());
If you think you will need to do something like that, include the Class argument in the method. Otherwise you may be getting ClassCastException at runtime, but this is easily debuggable, although it's not quite the idea behind generics.
Because ClassValidator is requiring a Class object as its parameter, NOT an instance of the class in question. Bear in mind you might be able to do what you're trying to do with this code:
ClassValidator<? extends T> validator = new ClassValidator<? extends T>(validateMe.getClass());