Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics and casting to the right type

Tags:

java

generics

My problem can be summed-up by this snippet:

public interface TheClass<T> {
    public void theMethod(T obj);
}

public class A {
    private TheClass<?> instance;

    public A(TheClass<?> instance) {
        this.instance = instance;
    }

    public void doWork(Object target) {
        instance.theMethod(target); // Won't compile!

        // However, I know that the target can be passed to the
        // method safely because its type matches.
    }
}

My class A uses an instance of TheClass with its generics type unknown. It features a method with a target passed as Object since the TheClass instance can be parameterized with any class. However, the compiler won't allow me to pass the target like this, which is normal.

What should I do to circumvent this issue?

A dirty solution is to declare the instance as TheClass<? super Object>, which works fine but is semantically wrong...

Another solution I used before was to declare the instance as raw type, just TheClass, but it's bad practice, so I want to correct my mistake.

Solution

public class A {
    private TheClass<Object> instance; // type enforced here

    public A(TheClass<?> instance) {
        this.instance = (TheClass<Object>) instance; // cast works fine
    }

    public void doWork(Object target) {
        instance.theMethod(target); 
    }
}
like image 505
Aurelien Ribon Avatar asked Mar 20 '12 10:03

Aurelien Ribon


1 Answers

public class A {
    private TheClass<Object> instance;

    public A(TheClass<Object> instance) {
        this.instance = instance;
    }

    public void do(Object target) {
        instance.theMethod(target); 
    }
}

or

public class A<T> {
    private TheClass<T> instance;

    public A(TheClass<T> instance) {
        this.instance = instance;
    }

    public void do(T target) {
        instance.theMethod(target);
    }
}
like image 135
khachik Avatar answered Sep 28 '22 08:09

khachik