dynamic loading of class
Im stuck with a very weird error
Let's say I have a class named Test.java in the same package as the main class
doing:
Class test = Class.forName("Test");
Object asdf = test.newInstance();
System.out.println(test.getName() );
does not throw exception and it will print the name of the class fine
but if i tried to ad
Test ta = (Test)asdf;
it threw InstantiationException with null on getMessage()
what is wrong in here?
thanks
this code will not throw an Exception
Object ta = asdf;
System.out.println("ta= " + ta.getClass().getName());
if you want to create another Test object, create if with the newInstance() method. Note that, if you load dynamically a Class, you cannot write Test ta = (Test)asdf;
because should import it to write this so the dynamic loading is unuseful.
Imports like this are not very usefull (although it should work), since you can directly instanciate the class anyway. It is more intersting if you don't know the classname at compiletime. Then you should cast to an interface.
I would be great to know that exception you got, and what the message was though.