Is not possible.
Java is a strong type language. This means that the compiler checks whether the methods and attributes you are accessing exist and are compatible with code usage. The only way to do this is if the compiler has access to the classes being used and the code is correctly importing these dependencies.
If it was possible to use weak typing as in scripting languages the cast would have no advantage, just call any method in the generic object and ready.
Anyway, what you’re trying to do is basically force Java to create a type dynamically without however presenting such a definition.
To access methods and attributes of dynamically loaded classes, you must use reflection. There are already some answers here, including mine that teach you how to do this, but basically you can use the method getMethod
of the class and retrieve a reference to the method, then you use the method invoke
to execute the method.
See an example taken from documentation:
public class InvokeMain {
public static void main(String... args) {
try {
Class<?> c = Class.forName(args[0]);
Class[] argTypes = new Class[] { String[].class };
Method main = c.getDeclaredMethod("main", argTypes);
String[] mainArgs = Arrays.copyOfRange(args, 1, args.length);
System.out.format("invoking %s.main()%n", c.getName());
main.invoke(null, (Object)mainArgs);
} catch (ClassNotFoundException x) {
x.printStackTrace();
} catch (NoSuchMethodException x) {
x.printStackTrace();
} catch (IllegalAccessException x) {
x.printStackTrace();
} catch (InvocationTargetException x) {
x.printStackTrace();
}
}
}
It would be possible to use
MyIn.cast(o)
but even then, you would not have the guarantee of which methods is composed the class of the objectMyIn
. Perhaps to execute this method, it would be possible to use reflection, if you know the names of the methods or have them in some xml, for example.– Gustavo Cinque