Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class abstraction and generics

Tags:

java

generics

I need to extend an abstract class which I can not modify:

public abstract class CustomField<T> extends AbstractField<T> implements HasComponents {
    // some code

    @Override
    public abstract Class<? extends T> getType();

    // some code
}

With a generic class like this:

public class VerticalCheckBoxSelect<T> extends CustomField<Set<T>> {

    @Override
    public Class<? extends Set<T>> getType() {
        return ???;
    }

}

My question is obvious: what should be returned by VerticalCheckBoxSelect::getType to be compilable (and correct)?

like image 799
Peter Vančo Avatar asked Sep 27 '22 07:09

Peter Vančo


2 Answers

You can return Class.class.cast(HashSet.class);

Which will compile, but will give you an unchecked assignment warning.

like image 86
Xanhast Avatar answered Oct 01 '22 23:10

Xanhast


Explanation

What you are actually doing is somehow equivalent to this,

public class VerticalCheckBoxSelect<T> extends CustomField<Set> {

    @Override
    public Class<? extends Set> getType() {
        return ???;
    }
}

Note that on the first line it says extends CustomField<Set> which means that public abstract Class<? extends T> getType() should be implemented in a way that it will always return Class<Set>, so your implementation should be:

public class VerticalCheckBoxSelect<T> extends CustomField<Set<T>> {

    @Override
    public Class<? extends Set<T>> getType() {
        @SuppressWarnings("unchecked")
        Class<Set<T>> r = (Class) Set.class;
        return r;
    }
}

The above code is now perfectly compilable. Try it!

Now, let's say that you want it to be of arbitrary subclass of Set like HashSet, then replace the above Set.class with HashSet.class:

public class VerticalCheckBoxSelect<T> extends CustomField<Set<T>> {

    @Override
    public Class<? extends Set<T>> getType() {
        @SuppressWarnings("unchecked")
        Class<Set<T>> r = (Class) HashSet.class;
        return r;
    }
}
like image 20
Jason Sparc Avatar answered Oct 01 '22 22:10

Jason Sparc