Reputation: 61
I have a flag telling me which class type to use. A static method should be used to retrieve the right class. The class type is needed as an input for a generic method.
public class Config{
public static int flag = 1;
}
public interface A {
public abstract int getResult();
}
public class A1 implements A{
public int getResult{
// ...
}
}
public class A2 implements A{
public int getResult{
// ...
}
}
public class AType{
public static Class getType(){
switch (Config.flag) {
case 1:
return A1.class;
case 2:
return A2.class;
default:
return null;
}
}
The return type of "getType()" is wrong. I already tried some generic return types, but as it seems it does not work like that to retrieve a class type for further usage...
Any ideas how to return a different class type depending on a configuration flag?
I need the class type (A1 or A2) as an input for generic methods like this one:
public static <T extends Message> T[] getArrayFromStream(DataInputStream in, Class<T> returnType)
throws IOException {
return getArrayFromStream(in, returnType, new Object[0]);
}
Upvotes: 2
Views: 2476
Reputation: 32949
My guess (given the lack of information) is that you are trying to do this:
Class clazz = getType();
A instance = clazz.newInstance();
If that is the case you need this...
public Class<? extends A> getType(){...}
and then
Class<? extends A> clazz = getType();
A instance = clazz.newInstance();
Upvotes: 4