I suspect this has been asked here (and answered) before, but I don't know how to name the problem. Why can I express the wildcards without problem only when I'm not passing the class itself?
It all boils down to this code. Everything works as expected except for the call to genericsHell(ShapeSaver.class):
interface Shape { }
interface Circle extends Shape { }
interface ShapeProcessor<T extends Shape> { }
class CircleDrawer implements ShapeProcessor<Circle> { }
class ShapeSaver<T extends Shape> implements ShapeProcessor<T> { }
class Test {
void genericsHeaven(ShapeProcessor<? extends Shape> a) {}
void genericsHell(Class<? extends ShapeProcessor<? extends Shape>> a) {}
void test() {
genericsHeaven(new CircleDrawer());
genericsHeaven(new ShapeSaver<Circle>());
genericsHell(CircleDrawer.class);
genericsHell(ShapeSaver.class); // ERROR: The method genericsHell is not applicable for the arguments (Class<ShapeSaver>)
}
}
The type of ShapeSaver.class is Class<ShapeSaver>. When feed it to genericsHell(), compiler needs to check if Class<ShapeSaver> is a subtype of Class<? extends ShapeProcessor<?>, which is reduces to whether ShapeSaver is a subtype of ShapeProcessor<?>. The subtype relation does not hold, the method call fails.
The same thing should be true for #Bohemian's solution. Here the subtype checking occurs at bound checking of T after T is inferred. It should fail too. This appears to be a compiler bug, which somehow misinterprets the rule that Raw is assignable to Raw<X> as if Raw is a subtype of Raw<X>. see also Enum.valueOf throws a warning for unknown type of class that extends Enum?
A simple solution to your problem is to declare
void genericsHell(Class<? extends ShapeProcessor> a)
indeed, ShapeSaver is a subtype of ShapeProcessor, and the call compiles.
That's not just a workaround. There's a good reason for it. Strictly speaking, for any Class<X>, X must be a raw type. For example, Class<List> is ok, Class<List<String>> is not. Because there is really no class that represents List<string>; there is only a class representing List.
Ignore the stern warning that you shall not use raw type. We must use raw types sometimes, given how Java type system is designed. Even Java's core APIs (Object.getClass()) use raw types.
You probably intended to do something like this
genericsHell(ShapeSaver<Circle>.class);
Unfortunately, that's not allowed. Java could have, but did not, introduce type literal along with generics. That created lots of problems for lots of libraries. java.lang.reflect.Type is a mess and unusable. Every library has to introduce their own representation of type system to solve the problem.
You can borrow one, e.g. from Guice, and you'll be able to
genericsHell( new TypeLiteral< ShapeSaver<Circle> >(){} )
------------------
(learn to skip the craps around ShaveSaver<Circle> when reading the code)
In the method body of genericsHell(), you'll have full type information, not just the class.
Typing the genericsHell method allows it to compile:
static <T extends ShapeProcessor<?>> void genericsHell(Class<T> a) {}
EDITED: This allows the compiler to specify from context, or by coding an explicit type, that the ShapeProcessor is not literally any ShapeProcessor, but the same type as the one passed as a parameter. If the call was explicitly typed, (which the compiler does under the covers) the code would look like this:
MyClass.<ShapeSaver>genericsHell(ShapeSaver.class);
Which interestingly, gives a type warning, but still compiles. The explicit type is not required however because sufficient type information is available from the parameter to infer the generic type.
Your question is missing some declarations, so I added them in to create a Short Self-Contained Correct Example - ie this code compiles as-is
static interface Shape { }
static interface Circle extends Shape { }
static interface ShapeProcessor<T extends Shape> { }
static class CircleDrawer implements ShapeProcessor<Circle> { }
static class ShapeSaver<T extends Shape> implements ShapeProcessor<T> { }
static void genericsHeaven(ShapeProcessor<? extends Shape> a) { }
// The change was made to this method signature:
static <T extends ShapeProcessor<?>> void genericsHell(Class<T> a) { }
static void test() {
genericsHeaven(new CircleDrawer());
genericsHeaven(new ShapeSaver<Circle>());
genericsHell(CircleDrawer.class);
genericsHell(ShapeSaver.class);
}
Related
This is an oversimplified version of the compiler behaviour I'm trying to understand:
class Scratch {
public static void main(String[] args) {
HouseCat<? extends Mammal> hcat = new Tabby();
//HouseCat<Mammal> won't work, compiler catches incorrect type parameter bound
HouseCat<CrazyHouseCat> crazyCat = new Tabby();
}
}
interface Mammal<T extends Mammal> extends Comparable<T>{
T cloneInstance();
}
interface Feline<T extends Feline> extends Mammal<T>{}
interface HouseCat <T extends HouseCat> extends Feline<T>{}
interface CrazyHouseCat<T extends CrazyHouseCat> extends HouseCat<T>{
void pushStuffOverTvStand();
}
class Tabby implements CrazyHouseCat<CrazyHouseCat>{
#Override
public CrazyHouseCat cloneInstance() {
return null;
}
#Override
public void pushStuffOverTvStand() {
}
#Override
public int compareTo(CrazyHouseCat o) {
return 0;
}
}
In the snippet above, HouseCat<? extends Mammal> is a reference with a wider range of types than that is allowed by the HouseCat interface, namely: HouseCat<T extends HouseCat>
If I were to try to do something like HouseCat<Long> the compiler would tell me that Long does not satisfy the type parameter's constraints. Well, so does not <? extends Mammal>, at least potentially.
The compiler would not let me create an instance that violates the type parameter T's constraints but I'm confused about its behaviour regarding the use of Mammal as the upper bound of the reference. There is an invalid type range between (HouseCat,Mammal] so why won't the compiler refuse this reference definition?
Clarification:
My question is not about the meaning of wildcard ?. I'm asking why the compiler is allowing a reference to a parameterised type instance be defined using a wider range of types than what is allowed by the parameterised type's definition. The mentioned questions do not address this specific case, they're about the meaning of a wildcard. My question is about the valid range of the wildcard, which the compiler does not seem be enforcing.
This looks like it answers your question. Basically HouseCat<? extends Mammal> allows to create a HouseCat<[insert type that extends Mammal here]>. All <? extends Mammal> does is act as a generic. In your example I don't see why you'd try to do it this way, but I hope this helps.
There are many threads relating to Java Generics, and I'm having trouble sorting out why exactly Java doesn't support this (or alternatively, what I need to do to make it work).
public interface Thinger<T> {
Class<? extends Thinger<T>> getThingers();
}
public class Thingy<Qwerty> implements Thinger<String> {
#Override
public Class<? extends Thinger<String>> getThingers() {
return Thingx.class;
}
}
public class Thingx implements Thinger<String> {
#Override
public Class<? extends Thinger<String>> getThingers() {
return Thingy.class; // Incompatible types error
}
}
I can fix the compile error two ways, but both of them end up dropping some kind of typing information that I want to keep!
Option 1
Drop the generic Qwerty in Thingy<Qwerty>.
public class Thingy implements Thinger<String> {
..
// Ends up fixing the compile error in Thingx
Option 2
Drop the generic String in Class<? extends Thinger<String>>
public class Thingx implements Thinger<String> {
#Override
public Class<? extends Thinger> getThingers() {
return Thingy.class; // Fixed!
Thingy.class returns a Class<Thingy> where Thingy is a raw type since it doesn't specify a value for Qwerty. Since, it's a raw type, the compiler is only aware of Thingy implementing Thinger, instead of Thinger<String>, since that information is lost due to type erasure.
To fix it, you can convert the Class<Thingy> to a Class<? extends Thinger> using Class#asSubclass, and then the compiler allows the implicit cast to Thinger<String>.
return Thingy.class.asSubclass(Thinger.class);
This produces no compiler or runtime errors when tested:
Class<? extends Thinger<String>> c = new Thingx().getThingers();
System.out.println(c.getGenericInterfaces()[0]);
Output is:
Thinger<java.lang.String>
I'm having trouble sorting out why exactly Java doesn't support this
Thingy.class has type Class<Thingy>, which is not a subtype of Class<? extends Thinger<String>>, because Thingy is not a subtype of Thinger<String>.
Note that since Thingy is a generic class (it is declared with a type parameter), using Thingy by itself without a type argument is a raw type. When you use a raw type, you disable all generics, so the supertype of Thingy (the raw type) is Thinger (the raw type), not Thinger<String> (even though Qwerty is not involved in the relationship). This is similar to how if you call a method on a raw type like Thingy, all generics are turned off in the parameter and return types of the method, even if they have nothing to do with Qwerty. This is just one of the reasons to avoid raw types.
It works for Thingx.class because Thingx is a subtype of Thinger<String>, as Thingx is not a raw type because the class Thingx is not generic.
As others have noted, there doesn't seem to be any reason why Thingy is generic, as the type parameter Qwerty is never used inside Thingy. So the best choice would be to remove it.
I've got problem in my code in Java. I have four(important) Classes:
public class RDOutput extends OutputType
public class RDAnalysis extends AnalysisProperties
Now I'm trying to make a method in Analysis properties:
public abstract void display(ArrayList<? extends OutputType> results);
The main problem list, the objects in the ArrayList will be different subtypes of OutputType. In my class RDAnalysis I try to make specific overriding:
public void display(ArrayList<RDOutput> results) {
but eclipse says: Name clash: The method display(ArrayList) of type RDAnalysis has the same erasure as display(ArrayList? extends OutputType) of type AnalysisProperties but does not override it
I'm not familiar with Java tricks, I tried searching in documentation and I didn't find any solution to this problem.
My question is: Is that trick that I'm doing (Basic type in abstract and Extended in final function) possible in Java (if yes, how can I do that?) or do I have to make some enum to solve this?
I suggest you to introduce generic parameter to your class and use it to parametrize your method:
public abstract class A<T extends OutputType> {
public abstract void display(ArrayList<T> results);
}
public class B extends A<RDOutput> {
public void display(ArrayList<RDOutput> results) {}
}
It's because your display doesn't cover every case of the abstract method. Maybe try something like this :
public class RDOutput extends OutputType {}
public class OutputType {}
public abstract class AnalysisProperties<T extends OutputType> {
public abstract void display(ArrayList<T> results);
}
public class RDAnalysis extends AnalysisProperties<RDOutput> {
#Override
public void display(final ArrayList<RDOutput> results) {
}
}
The problem is that you try to override a method while restricting possible parameters.
=> ArrayList<? extends OutputType> accepts more possible elements than ArrayList<RDOutput> since RDOutput extends OutputType.
You break the rule that says: the concerned subclass method has to encompass at least elements of superclass one and NEVER restrict them.
So compiler avoid to valid this override.
By the way, avoid to type your reference with concrete values like ArrayList.
What about a LinkedList passed as arguments? ... prefer a more generic relevant type like List.
Problem here is that, after type erasure comes into play, the signature of the two methods are undistinguishable: they have the same return type and they can both accept a ArrayList<RDOutput> but the first one (the generic one) can also accept any ArrayList<T extends OutputType>.
This mean that, although the JVM won't be able to choose which one to call at runtime if you pass an ArrayList<RDOutput>, at the same time your display method does not override the abstract one because your method only work for lists of RDOutput, so if you pass a List<T extends OutputType> with T != RDOutput your specific implementation doesn't accept it.
You should consider using a type parameter on the whole class as suggested in other answers, or accept the fact that you won't be able to use any RDOutput specific methods in your display method without a cast.
if a method is expecting ArrayList<? extends OutputType>
ArrayList<RDOutput> cannot be passed to it, as parent type allows any child class of OutputType in arraylist.
consider a code like this
AnalysisProperties properties = new RDAnalysis();
properties.display(arraylist consisting of any child class of OutputType); //this line will cause runtime problems
I have a class which has a self referential generic parameter and a parameter which is of the same super class. The static function has identical bounds as the class.
public class Bar<T extends Bar<T, C>, C extends Bar<C, ?>> {
Bar() {
foo((T) null);
foo((C) null);//compile error
}
static <S_T extends Bar<S_T, S_C>, S_C extends Bar<S_C, ?>> void foo(S_T t) {
}
}
This gives the following error.
Bound mismatch: The generic method foo(S_T) of type Bar<T,C> is not
applicable for the arguments (C). The inferred type C is not a valid
substitute for the bounded parameter <S_T extends Bar<S_T,S_C>>
I can't figure out why C can't be passed in to foo() since C is Bar<C,?> and the wildcard is a Bar because of the second parameter in the declaration says it extends Bar.
I know this is probably a bad idea and produces code which is hard to understand but I really wanna know why this doesn't compile.
The short answer is that Java type inference is actually pretty lame.
Java is not performing any intelligent inference on the wildcard ? in the declaration of Bar to infer that it is logically bounded by Bar< ?, ? > (nor that the ?s in that bound are themselves bounded, and so on). Once you put ? by itself, that's all Java knows. Although nothing is stopping you from putting that bound in on the wildcard in the declaration of Bar, even that does not help Java; Java won't ever assume that two separate ?s refer to the same type, even if deeper analysis would imply that they have to be. In other words, the compile error persists even with this code:
public class Bar<T extends Bar<T, C>, C extends Bar<C, ? extends Bar<?, ? extends Bar<?, ?>>>> {
Bar() {
foo((T) null);
foo((C) null);//compile error
}
static <S_T extends Bar<S_T, S_C>, S_C extends Bar<S_C, ? extends Bar<?, ? extends Bar<?, ?>>>> void foo(S_T t) {
}
}
I'm not a crack with generics, but I think the problem is that you declare the type of foo() to be
<S_T extends Bar<S_T,S_C> > void foo(S_T)
and then call it in two different contexts that require a different static type for foo().
In the fist context S_T has type T and in the second context it has type C. But T and C are declared as Bar<T,?> and Bar<C,?>, which are incompatible types statically.
I would guess that the compiler figures out the type of foo() in the first call and then assumes correctly, that the type must remain the same throughout, which it doesn't.
I have an abstract Class Monitor.java which is subclassed by a Class EmailMonitor.java.
The method:
public abstract List<? extends MonitorAccount> performMonitor(List<? extends MonitorAccount> accounts)
is defined in Monitor.java and must be overridden in EmailMonitor.java.
I currently have the method overridden in EmailMonitor.java as follows:
#Override
public List<EmailAccount> performMonitor(List<EmailAccount> emailAccounts) {
//...unrelated logic
return emailAccounts;
}
However, this produces the compile time error:
Name clash: The method performMonitor(List<EmailAccount>) of type EmailMonitor has the same erasure as performMonitor(Lis<? extends MonitorAccount> emailAccounts) of type Monitor but does not override it
EmailAccount is a subclass of MonitorAccount, so (in my mind at least) overriding it in this way makes perfect sense. Seeing as the compiler is not happy with my logic though, How should I go about this correctly while still keeping my compile time checks to make sure that all calls to EmailMonitor.performMonitor() receive Lists of EmailAccount rather than some other type of MonitorAccount?
No, it's not overriding it properly. Overriding means you should be able to cope with any valid input to the base class. Consider what would happen if a client did this:
Monitor x = new EmailMonitor();
List<NonEmailAccount> nonEmailAccounts = ...;
x.performMonitor(nonEmailAccounts);
There's nothing in there which should give a compile-time error given your description - but it's clearly wrong.
It sounds to me like Monitor should be generic in the type of account it can monitor, so your EmailMonitor should extend Monitor<EmailAccount>. So:
public abtract class Monitor<T extends MonitorAccount>
{
...
public abstract List<? extends T> performMonitor(
List<? extends T> accounts);
}
public class EmailMonitor extends Monitor<EmailAccount>
{
#Override
public abstract List<? extends EmailAccount> performMonitor(
List<? extends EmailAccount> accounts)
{
// Code goes here
}
}
You might want to think carefully about the generics in the performMonitor call though - what's the return value meant to signify?
Here is my own solution. I suspect this is the same thing Jon Skeet was trying to get at... without the typo (see my comment in reply to his answer).
the Monitor.java class:
public abstract class Monitor <T extends MonitorAccount> {
...
public abstract List<T> performMonitor(List<T> accounts);
..
}
EmailMonitor.java
public class EmailMonitor extends Monitor<EmailAccount> {
...
public List<EmailAccount> performMonitor(List<EmailAccount> emailAccounts) {
..//logic...logic...logic
return emailAccounts;
}
...
}
In this configuration, EmailMonitor.performMonitor() will always check at compile time that it receives a list of EmailAccount rather than any of my other types FTPAccount, DBAccount, etc... It's much cleaner than the alternative, which would have been receiving/sending a raw list and then having to coerce it the required type resulting in potential runtime type casting exceptions.