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);
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With