Class Loader Problem

M

Mani

Hi
I am loading a class dynamically and i am using classloader.My code
looks like this and its working fine.

import java.lang.reflect.Method;

public class TestTwo{
TestTwo(){}
void Create() throws Exception{
c.TestOne t ;
ClassLoader cl = this.getClass().getClassLoader();
Class cla = cl.loadClass("c.TestOne");
t = (c.TestOne) cla.newInstance();
System.out.println(t.getI());
Method[] methArr = cla.getDeclaredMethods();
for (int o=0; o< methArr.length; o++){
//To get Public methods out of the class
if(methArr[o].getModifiers()==java.lang.reflect.Modifier.PUBLIC)
System.out.println(methArr[o].getName());
}
}

public static void main(String[] args){

TestTwo t = new TestTwo();
try {
t.Create();

}
catch (Exception e) {e.printStackTrace();}
}
}

My doubt is i am having testone class inside this package
(c.testone)and suppose i am placing the class testone somewhere else
the code is not working fine..
My question is can we dynamically load a class dynamically from
anywhere in my system.

thanks for your reply in advance
 
J

John C. Bollinger

Mani said:
Hi
I am loading a class dynamically and i am using classloader.My code
looks like this and its working fine.

import java.lang.reflect.Method;

public class TestTwo{
TestTwo(){}
void Create() throws Exception{
c.TestOne t ;
ClassLoader cl = this.getClass().getClassLoader();
Class cla = cl.loadClass("c.TestOne");
t = (c.TestOne) cla.newInstance();

Those last three lines are totally pointless. You can replace them with

t = new c.TestOne();

for identical effect. It is never useful to reflectively load a class
whose name is known at compile time.

What are you trying to accomplish with this?
My doubt is i am having testone class inside this package
(c.testone)and suppose i am placing the class testone somewhere else
the code is not working fine..
My question is can we dynamically load a class dynamically from
anywhere in my system.

You can always use a ClassLoader to load any class among those available
to it, which usually means from among those in its class path.
("Usually" because certain custom class loaders might use means other
than a class path to find and load classes.) If you are using your
application's own system ClassLoader (as above) then you can load any
class no matter the package or location, so long as that class can be
found in the application's class path.


John Bollinger
(e-mail address removed)
 

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

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,192
Latest member
KalaReid2

Latest Threads

Top