Java generics - Class<? extends Base> - java

I'm confused a bit about Java generics.
I have a class Test which extends from Base:
public class Test extends Base {
private final static Test obj = new Test();
new Auto(obj);
}
The constructor of Auto is like this (not my class):
public Auto (Class<? extends Base> programclass) {}
And I'm getting this error:
Test cannot be converted to Class<? extends Base>
How should I declare obj variable so I can pass it to Auto constructor?
Thanks

Related

Java weird generic's behavior

I found some weird behavior for java generics. I can't use parametrized class, which implements another parametrized class, in parametrized method.
It sounds messy, so let's look at the code:
class A {
public<RESP extends Serializable, REQ extends Serializable> RESP sendData(REQ req, Class<? extends I<RESP, REQ>> c) {
return null;
}
}
interface I<RESP extends Serializable, REQ extends Serializable> {
}
class B implements I<String, Integer> {
A a;
public void test() {
a.sendData(1, getClass());
}
}
It compiles fine. But we can break it easily. Just add a parameter variable to class B:
class B<T> implements I<String, Integer>
Now a.sendData(1, B.class); has the compiler error:
method sendData in class A cannot be applied to given types;
required: REQ,Class<? extends I<RESP,REQ>>
found: int,Class<B>
reason: cannot infer type-variable(s) RESP,REQ
(argument mismatch; Class<B> cannot be converted to Class<? extends I<RESP,REQ>>)
where REQ,RESP are type-variables:
REQ extends Serializable declared in method <RESP,REQ>sendData(REQ,Class<? extends I<RESP,REQ>>)
RESP extends Serializable declared in method <RESP,REQ>sendData(REQ,Class<? extends I<RESP,REQ>>)
I just added unused parameter to class signature!
Can anyone explain why this happens and is there way to use type variable in class B?
Actualy my goal is signature for class B like this:
class B<Data> implements I<String, ? extends List<Data>>
By the way, I try this code in Java 8.

how can a Class.forName returns a Class<? extends MyAbstractClass>?

Let's say I have an abstract class MyAbstractClass:
public abstract class MyAbstractClass {
public abstract SomeObject doSomething();
}
and I have some concrete implementations of this class, MyConcreteClass1 and MyConcreteClass2.
Let's say I read the class name of any of the concrete implementations from a file and then I want to create the object:
String concreteImplementationName = getConcreteImplementationName();
Class<?> klass = Class.forName(concreteImplementationName);
I get the Class and then using reflection I can instantiate an object.
Now, in this case I know that the concreteImplementationName will only contain the name of one of the implementations of MyAbstractClass. How can I convert klass to a Class<? extends MyAbstractClass>?
Class<? extends MyAbstractClass> x = // what do I need to do here?
You can use Class.asSubclass to do this. It works similarly to a cast, but for a Class object.
c.asSubclass(T.class) will check that c is actually a subclass of T, and if so it will return a Class<? extends T>. Otherwise it will throw a ClassCastException.
So you want this:
Class<? extends MyAbstractClass> x = klass.asSubclass(MyAbstractClass.class);
Just add a cast. You can do this safely because you know it's a subtype of MyAbstractClass
public class Example {
public static void main(String[] args) throws Exception {
String concreteImplementationName = "com.example.Implementation";
Class<? extends MyAbstractClass> x = (Class<? extends MyAbstractClass>) Class.forName(concreteImplementationName); // what do i need to do
}
}
class Implementation extends MyAbstractClass {
}
class MyAbstractClass {
}

Can't add children.class to set of parent.class

I am trying to add the class object of a children class to a set of parent class object :
public class Main {
public static void main(String[] args) {
Set<Class<? extends A<?>>> set = new HashSet<>();
set.add(C.class); //this does not work
}
public abstract class A<T> {
}
public abstract class B<T, V> extends A<T> {
}
// Set<T> could be any other class, it is for demonstration purpose.
public class C<T> extends B<Set<T>, Set<T>> {
}
}
I get the following error :
The method add(Class<? extends Main.A<?>>) in the type Set<Class<? extends Main.A<?>>> is not applicable for the arguments (Class<Main.C>)
If I remove the '?' from the A, the code compiles, but I don't understand why. Can someone explain me why the "add" is not working ?
class is a 'class literal' which only looks like a static field.
As per definition, the type of C.class is Class<C>, where C is the name of a class.
So you cannot add it to a Set of Class<C<?>> (or in your case Set<Class<? extends A<?>>>)
For further information read 15.8.2 Class Literals in the Java specs:
http://docs.oracle.com/javase/specs/jls/se8/jls8.pdf

Java generics: <B extends BaseB> does not match <? extends BaseB>

I have two isomorphic type hierarchies. The base type of the first one is BaseA and the base type of the second one is BaseB. I know how to transform any object of any subclass of BaseB to its corresponding subtype of BaseA. I want to implement a method which takes object of type BaseB determines its class and constructs an object of the corresponding subtype of BaseA. Example code:
public interface BaseA...
public interface BaseB...
public class DerA implements BaseA...
public class DerB implements BaseB...
...
public interface Transform<A,B> {
A toA (B b);
}
public class DerAtoDerB implements Transform<DerA,DerB> {
DerA toA (DerB b){...}
}
public class Transformations {
private static Map<Class<?>, Transform<? extends BaseA, ? extends BaseB>> _map =
new HashMap<>();
static {
_map.put(DerB.class, new DerAtoDerB());
}
public static <B extends BaseB> BaseA transform(B b){
Transform<? extends BaseA, ? extends BaseB> t = _map.get(b.getClass());
return t.toA(b); // Compile error: Transform<A,B#2> cannot be applied to given types
}
Why <B extends BaseB> is not compatible with <? extends BaseB> ? Also if I try implementing the static transform method like this:
public static BaseA transform(BaseB b){
Transform<? extends BaseA, ? extends BaseB> t = _map.get(b.getClass());
return t.toA(b); // Compile error: Transform<A,B> cannot be applied to given types
}
I get a compilation error: Transform<A,B> cannot be applied to given types
Can anyone explain me what I am doing wrong with Generics?
The problem is that in the transform method the compiler can't know that the type parameter B extends BaseB and the second type parameter in the Transform class (? extends BaseB) that was gotten from the map actually represent the same subclass of BaseB. Nothing stops you from storing an incompatible type in the map:
_map.put(DerB.class, new AnotherDerAtoAnotherDerB()); // the types don't match
You are the one who guarantees that the types in the map match, so you need to tell the compiler by casting it to the correct type:
#SuppressWarnings("unchecked")
public static <B extends BaseB> BaseA transform(B b) {
Transform<? extends BaseA, B> t =
(Transform<? extends BaseA, B>)_map.get(b.getClass());
return t.toA(b);
}
When the compiler encounters a variable with a wildcard in its type it knows that there must have been some T that matches what was sent in. It does not know what type T represents, but it can create a placeholder for that type to refer to the type that T must be. That placeholder is called the capture of that particular wildcard.
I don't know why the compiler can't figure out that capture<? extends BaseB> could be capture<?> extends BaseB, maybe something with type erasure?
I would instead implement it like this:
interface BaseA {}
interface BaseB {}
class DerA implements BaseA {}
class DerB implements BaseB {}
interface Transform {
BaseA toA(BaseB b);
}
class DerAtoDerB implements Transform {
public BaseA toA(BaseB b) { return new DerA(); }
}
class Transformations {
private static Map<Class<?>, Transform> _map =
new HashMap<>();
static {
_map.put(DerB.class, new DerAtoDerB());
}
public static<B extends BaseB> BaseA transform(B b) {
Transform t = _map.get(b.getClass());
return t.toA(b);
}
}
? means unknown type.
When a variable is of type X you can assign it a value of type X or any subtype of X but "? extends X" means something else.
It means there is an unknown type that may be X or any subtype of X. It is not the same thing.
Example:
public static Transform<? extends BaseA, ? extends BaseB> getSomething(){
// My custom method
return new Transform<MySubclassOfA, MySubclassOfB>(); // <-- It does not accept BaseB, only MySubclassOfB
}
public static BaseA transform(BaseB b){
Transform<? extends BaseA, ? extends BaseB> t = getSomething();
return t.toA(b); // <--- THIS IS WRONG, it cannot accept any BaseB, only MySubclassOfB
}
In the example the compiler does not know if t admits any BaseB or what but I shown an example where it doesn't.
This thing compiles:
package com.test;
import java.util.HashMap;
import java.util.Map;
interface BaseA{}
interface BaseB{}
class DerA implements BaseA{}
class DerB implements BaseB{}
interface Transform<A,B> {
A toA (B b);
}
class DerAtoDerB implements Transform<BaseA,BaseB> {
public DerA toA(DerB b){ return null; }
#Override
public BaseA toA(BaseB baseB) {
return null;
}
}
public class Transformations {
private static Map<Class<?>, Transform<? extends BaseA, ? super BaseB>> _map = new HashMap<Class<?>, Transform<? extends BaseA, ? super BaseB>>();
static {
_map.put(DerB.class, new DerAtoDerB());
}
public static <B extends BaseB> BaseA transform(B b){
Transform<? extends BaseA, ? super BaseB> t = _map.get(b.getClass());
return t.toA(b);
}
}
The changes I made to your code are the following:
DerAtoDerB now implements Transform<BaseA,BaseB>, instead of Transform<DerA,DerB>
Type of second generic parameter of Map has changed to Transform<? extends BaseA, ? super BaseB> - pay attention to use of super instead of extends - it's the opposite type bound.
Main concept of Java generics: if ChildClass extends ParentClass it DOES NOT mean YourApi<ChildClass> extends YourApi<ParentClass>. E.g.:
NumberTransform<String, ? extends Number> intTransform = new IntegerTransform<String, Integer>(); // work with Integer numbers only
NumberTransform<String, ? extends Number> longTransform = new LongTransform<String, Long>(); // work with Long numbers only
longTransform.toA((Integer) 1); // you are trying to make this and got compilation error.
To help compiler replace your t initialization:
Transform<? extends BaseA, B> t = (Transform<? extends BaseA, B>) _map.get(b.getClass());

How to load a custom class inherited from existing one?

I'm trying to create an object of a class, using just a name of this class:
public interface Foo {
}
public class Bar implements Foo {
}
[...]
Class<Foo> c = Class.forName("com.XXX.Bar").asSubclass(Foo.class);
Foo foo = c.newInstance();
Compiler says:
incompatible types found :
java.lang.Class<capture#47 of ? extends com.XXX.Foo>
required: java.lang.Class<com.XXX.Foo>
What's wrong here?
Since c is a some class which extends Foo, you should express it in the code using <? extends ...> syntax:
Class<? extends Foo> c = Class.forName("com.XXX.Bar").asSubclass(Foo.class);

Categories