Hello,
I'm having a problem casting cast from an object in GWT. I have a public <T> T getInstance(Class<T> clazz, String code,String packageName)
method which, upon receiving a class, a code and a package name, generates an instance of the passed code and converts it to the type of the parameter class with the package also supplied. Here's the implementation:
public <T> T getInstance(Class<T> clazz, String code,String packageName)
throws IOException, InstantiationException, IllegalAccessException, NameNotFoundException {
final String name = getClassName(code);
final Path wrappedCodede = wrapCode(packageName, name, code);
final Path classFile = compile(wrappedCodede);
final ClassLoaderFromTemp loader = new ClassLoaderFromTemp();
final Class<?> p1Class = loader.findClassInTemp(classFile);
final Object instace = p1Class.newInstance();
cleanupTmp();
return clazz.cast(instace);
}
When I call this method by passing the code to be compiled and instantiated through GWT, I get a ClassCastException exception thrown at clazz.cast(instace)
. However, it would be plausible for such an exception to be launched if it were not for the following reasons which contradict it:
- Both the class passed by parameter and the superclass of the generated instance of the code are the same.
- Calling the same method, however outside of GWT (by a
main
method in the context of aJava Application
execution) works without any problem. See below an example of a method call that does not throw the exception.
Calling the method outside GWT:
public static void main(String[] args) {
try {
AgentBuilder.addToClassPath("src");
AgentBuilder ab = new AgentBuilder();
ab.getInstance(Ship.class, CODE, "Teste");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Now see a method that throws the exception, but only if executed as a Web Application next to GWT:
void checkCode() throws SoncException {
try {
AgentBuilder agentBuilder = new AgentBuilder();
agentBuilder.getInstance(Ship.class, this.code, this.nick);
} catch (IOException | InstantiationException | IllegalAccessException | NameNotFoundException
| NullPointerException | ClassCastException e) {
throw new SoncException("An error occurred on checking player's code.", e);
}
}
For both the first and second method, consider the argument code
passed in the call of getInstance
as import sonc.battle.Ship; public class EmptyShip extends Ship {}
.
Would anyone have any idea why this exception should be thrown in one case and the other not?
Thanks for the help, guys.