Why does my general method stop working?

In my project, I have a factory method that loads an object that implements the interface. You go in the class you want and get it like that.

public class Factory { public static <E extends SomeInterface> E load( Class<E> clss ) throws Exception { return clss.newInstance(); } } 

You can call it like this:

 MyObject obj = Factory.load( MyObject.class ); 

This code works fine in Eclipse 3.4 with Java 6u13, however today I got a new laptop and installed Eclipse 3.5 and java 6u15 and now I get type mismatches everywhere.

 MyObject obj = Factory.load( MyObject.class ); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Type mismatch: cannot convert from SomeInterface to MyObject 

Putting a cast to factory on this line makes it go away, and everything works fine, but makes the line a little less clean, and I don't need it before, so what?

+4
source share
4 answers

Is this all the code needed to get this error? I saw something very similar in some code that I watched today. An additional parameter has been added to the equivalent of your Factory method, which also had a generic type. This lacked this general definition, and I believe that this was the reason that it was confusing the compiler.

those. if your Factory method looked something like

 public class Factory { public static <E extends SomeInterface> E load( Class<E> class, Key key ) { // return an instance of E } } 

Where there is some Class class defined by something like this

 public class Key<Datatype> { .... } 

When providing something like this to call a method, don’t mark any generics of the ad declaration

 Key key = new Key() MyObject obj = Factory.load( MyObject.class, key ); 

Hope this helps,

+1
source

Have you recently added a type parameter to your factory class? There is a trap with common methods for raw types:

  public class FooFactory<UnrelatedArg> { public <E> E load(Class<E> c) { ... } } FooFactory<?> f; f.load(String.class); // returns String FooFactory f; f.load(String.class); // returns Object 
+2
source

I think this is due to the Java compilation level. By default, the project has a default level. Which you installed in the Eclipse settings. In your old installation, you change it.

0
source

All Articles