开发者

Java ClassLoader Basics

开发者 https://www.devze.com 2023-03-31 14:41 出处:网络
I have a need for a personal command-line tool that should take the name of a concrete subclass as a CL argument and instantiate the correct Java class at runtime:

I have a need for a personal command-line tool that should take the name of a concrete subclass as a CL argument and instantiate the correct Java class at runtime:

public class MyCommandLineTool
{
    public static void main(String[] args)
    {
        // Read the name of the desired class to load
        String strClassName = getClassNameFromArgs(args);

        // Now create an instance of that class (if it exists/is valid/etc.)
        Shape oShape = someMagicalClassLoaderCall(strClassName);

        // Now call the subclass's overridden draw() method
        oShape.draw();
    }
}

public abstract class Shape
{
    // Some stuff

    public abstract void draw();
}

public class Circle extends Shape
{
    @Override
    public void draw()
    {
        // etc...
    }
}

Therefore, from the command line, you might run the program as follows:

java MyCommandLineTool -shape Circle

Or something like that (not worried about the sy开发者_如何学Cntax of the command line call right now).

I've read several introductory tutorials on ClassLoaders, but am choking on understanding when one needs to write their own class loader. All the tutorials seem to focus on how to write your class loader, but without explaining when it is appropriate to do so. And, because it seems fairly complicated to do this, I would prefer to not have to write my own if I don't have to.

It seems to me that if I have a compiled Circle.class file, any JVM should have no problem reading that class file and constructing an instance of a Circle at runtime based on a string I pass it containing that class's name.

Can anyone clarify whether or not I need to write my own loader for this specific example, why, and if not, what I need to implement in lieu of someMagicalClassLoaderCall(String).

Thanks!


You'll have to make sure that the actual class is on the classpath when you run your program

Class clazz = Class.forName("fully.qualyfied.ClassName");
Shape instance = (Shape)clazz.newInstance();
instance.draw()


You shouldn't need to write your own class loader for that - just specify the classpath correctly. Something like this should work:

String className = 'Circle';
Class myClass = Class.forName(className);
Object ofMyClass = myClass.newInstance();


It should be as easy as:

Class c = Class.forName(strClassName);
Object o = c.newInstance();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号