Class's newInstance() method returning null

R

Rick

I am using a custom ClassLoader to load a class. The class loads fine,
but the instantiation with Class's newInstance() method returns a
null.

Code snippet:
TestClassLoader loader = new TestClassLoader(dirName);
System.out.println("\n\ntest = " + test + "\n");
Class c = Class.forName("tests.Kiv7Test",true,loader);
Object t = c.newInstance(); //OBJECT t is NULL!!!
System.out.println("Class loaded: " + c.getName () + " Object:" + t +
" isInstance: " + c.isInstance (t));

Output:
test = tests.Kiv7Test

default Kiv7Test
Class loaded: tests.Kiv7Test Object:null(tests.Kiv7Test) isInstance:
true


The "default Kiv7Test" output is a simple println() in the Kiv7Test
no-arg constructor, so we know the Kiv7Test was loaded, instantiated,
and ran properly.

Any advice on how to overcome this situation (and an explanation of
what I'm doing wrong) would be appreciated.

TIA!

-Rick
 
L

Lee Fesperman

Rick said:
I am using a custom ClassLoader to load a class. The class loads fine,
but the instantiation with Class's newInstance() method returns a
null.

Code snippet:
TestClassLoader loader = new TestClassLoader(dirName);
System.out.println("\n\ntest = " + test + "\n");
Class c = Class.forName("tests.Kiv7Test",true,loader);
Object t = c.newInstance(); //OBJECT t is NULL!!!
System.out.println("Class loaded: " + c.getName () + " Object:" + t +
" isInstance: " + c.isInstance (t));

Output:
test = tests.Kiv7Test

default Kiv7Test
Class loaded: tests.Kiv7Test Object:null(tests.Kiv7Test) isInstance:
true

The "default Kiv7Test" output is a simple println() in the Kiv7Test
no-arg constructor, so we know the Kiv7Test was loaded, instantiated,
and ran properly.

Any advice on how to overcome this situation (and an explanation of
what I'm doing wrong) would be appreciated.

If your code snippet is correct, t is not null. Its toString() is returning
"null(tests.Kiv7Test)" and c.isInstance is returning true.

To double check, add this to your println: + "t-is-null=" + (t==null)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top