Question

Here is a code that uses Javassist for generating classes on the fly.

public class ClassGenerator {

    // ...

    public Class<? extends Base> generateClass(MetaData md) {
         // Call javassist api and returns a generated on the fly class...
    }
}

Later in the code, there is

public class GeneratorClient implements IClient<Base> {
   private Class<Base> clazz;

   public void init() {
      MetaData myMd = ...;

      clazz = generator.generateClass(myMd);

      // ...
   }

   public Base getClazz() {
       return clazz;
   }
}

public interface IClient<T extends Base> {
    T getClazz();
}

Obviously, the compiler raises an error here. Casting raises a warning ("Uncheked cast ...")...

Suppressing the warning is not an option.

I can't write this also : public class GeneratorClient implements IClient<? extends Base>.

How can I change the return type of ClassGenerator#generateClass ?

JDK 6

Was it helpful?

Solution

Change your GeneratorClient declaration to this:

public class GeneratorClient<T extends Base> 
    implements IClient<T>
{
    private final Class<T> clazz;
    // etc

This should do it.

EDIT Since you only know the class at runtime, add a static factory method to build your GeneratorClient:

public static <T extends Base> GeneratorClient<T> forClass(final Class<T>)
{
    return new GeneratorClient<T>(whatever, args, are, needed, if, any);
}

In code:

final GeneratorClient<MyClass> = GeneratorClient.forClass(MyClass.class);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top