简体   繁体   中英

How to use ClassLoader or Class to programatically load a Class

I have two classes

package pack2;
import java.lang.*;
import java.io.*;
class eg
{
    public void show()
    {
        System.out.println("ClassPath set to this class");
    }
}

this is in C:\\NNK\\pack2. the fully qualified name is pack2.eg

another program is

import java.io.*;
import java.lang.*;
import java.net.*;
class classload
{
    public static void main(String args[])
    {
        //have to load the eg class here. Dont know what i have done below is right or wrong
        try 
        {
            Class b=Class.forName("pack2.eg");
        }
        catch(ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        try
        {
            eg z=(eg) b.newInstance();
        }
        catch(InstantiationException l)
        {
            l.printStackTrace();
        }
        z.show();
        System.out.println("b.getName()="+b.getName());
    }
}

this program is at C:\\NNK I have to load the eg program here. I tried to learn it in Oracle saw other related stack overflow questions of it. Dynamically loading a class in Java But it didn't work i keep getting the error b is Unknown and z is unknown symbol. Also is there a way to use the directory filename(eg: C:\\NNK\\pack2\\eg) to load a class

In addition to multiple errors already identified by Jim Garrison answer, you've declared your class with "default" scope. This means it can only be referenced via classes in the same package.

should be

public class eg   // <== public
{
    public void show()
    {
        System.out.println("ClassPath set to this class");
    }
}

And no need for separate try catches, why not just throw from the main method... If any step failed, eg defining b, you couldn't do anything more anyway...

public static void main(String[] args) throws Exception {

    Class b = Class.forName("pack2.eg");
    eg z = (eg)b.newInstance();
    z.show();

    System.out.println("b.getName()=" + b.getName());
}

This is a scope issue. Move the declarations of b and z outside the first try , as in:

public static void main(String args[])
{
    //have to load the eg class here. Dont know what i have done below is right or wrong
    Class b;
    eg z;
    try 
    {
        b=Class.forName("pack2.eg");
    }
    catch(ClassNotFoundException e)
    {
        e.printStackTrace();
    }
    try
    {
        z=(eg) b.newInstance();
    }
    catch(InstantiationException l)
    {
        l.printStackTrace();
    }
    z.show();
    System.out.println("b.getName()="+b.getName());
}

You will probably have to make pack2.eg public as well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM