Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eliminate type parameter of java generics

Tags:

java

generics

The code:

interface Property<T>
{
    T get();
}

class BoolProperty implements Property<Boolean>
{
    @Override
    public Boolean get()
    {
        return false;
    }
}
class StringProperty implements Property<String>
{
    @Override
    public String get()
    {
        return "hello";
    }
}
class OtherStringProperty implements Property<String>
{
    @Override
    public String get()
    {
        return "bye";
    }
    public String getSpecialValue()
    {
        return "you are special";
    }
}

is used by my class:

class Result<P extends Property<X>, X>
{
    P p;
    List<X> list;
}

As you see it has two type parameters P and X. Despite of that the X can always be deduced from P but the language requires me to supply both:

Result<BooleanProperty, Boolean> res = new Result<BooleanProperty, Boolean>();

Is there any trick to get rid of the X type parameter? I want just use

Result<BooleanProperty> res = new Result<BooleanProperty>();

Also, I don't want lose type information and use it as:

Result<OtherStringProperty> res = new Result<OtherStringProperty>();
String spec = res.p.getSpecialValue();
String prop = res.list.get(0);
like image 886
kan Avatar asked Dec 07 '11 14:12

kan


People also ask

How do I restrict a generic type in Java?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.

What is type erasure in Java generics?

Type erasure is a process in which compiler replaces a generic parameter with actual class or bridge method. In type erasure, compiler ensures that no extra classes are created and there is no runtime overhead.

What is type parameters in generics?

In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they create an instance of the generic type.

Why are generics implemented using type erasure?

Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to: Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded.


1 Answers

I would change Result class to be something like

class Result<X> {
    Property<X> property;
    List<X> list;
}

I don't think the compiler can infer X from Property, as your Result class is waiting two definitions for the two generics.

like image 80
Caesar Ralf Avatar answered Sep 28 '22 02:09

Caesar Ralf