Problem compiling with Generic
I have a problem in compilation with the following code, I tried a lot of possibilities except the one I corrected my problem (I have missed something). The code in question, I deliberately simplify my code
Code:
import java.util.*;
public class BugCompiler
{
interface IObjectFactory<T>
{
public T createObject();
public Class<T> getObjectClass();
}
class StringObjectFactory implements IObjectFactory<String>
{
@Override
public String createObject()
{
return "test";
}
@Override
public Class<String> getObjectClass()
{
return String.class;
}
}
class ArrayListObjectFactory implements IObjectFactory<ArrayList<String>>
{
@Override
public ArrayList<String> createObject()
{
return new ArrayList<String>();
}
@Override
public Class<ArrayList<String>> getObjectClass()
{
return ArrayList.class;
}
}
}
Re: Problem compiling with Generic
It's not very clean but the following code compiles
Code:
public Class<ArrayList<String>> getObjectClass()
{
return (Class<ArrayList<String>>) new ArrayList<String>().getClass();
}
Re: Problem compiling with Generic
Indeed it is not very clean. In the present circumstances, Class <ArrayList <String>> does not exist!
At runtime you can not know the typeage Generics of a class!
Re: Problem compiling with Generic
Is it not possible to change my interface to be cleaner code? Is there a way by changing my interface to define the class?
Code:
interface IObjectFactory<T>
{
public T createObject();
public Class<T> getObjectClass();
}
Re: Problem compiling with Generic
You can try by fiddling a bit:
Code:
@SuppressWarnings("unchecked")
private <R> R unsafeCast(Object t) {
return (R) t;
}
public Class<ArrayList<String>> getObjectClass() {
return unsafeCast(ArrayList.class);
}
But in the type ArrayList<String> means nothing to the performance.