[java] Loading a custom class

Started by
1 comment, last by Son of Cain 18 years, 1 month ago
How would I load a custom class? Say Foo.class, with an array of integers. I was hoping there would be a simple way to do this. I tried URLClassLoader, but it gives me tons of errors. It seems more then what I need anyways, there should be an easy way to do this. kinda like this but evaluate the string "Foo" foo = new "Foo"(); I want to be able to load variable name classes. Is this possible? Practical? (For Maps in a rpg for example)
Advertisement
You need a ClassLoader when the class hasn't been loaded yet. If the class is already loaded, you could use something like this...

[source=java]try {    Class yourClass = Class.forName("somepackage.YourClass");    Class[] contstructorParamTypes =        {String.class, int.class, SomethingElse.class};    Object[] constructorParams = new Object[3];    constructorParams[0] = "First param";    constructorParams[1] = new Integer(23);    constructorParams[2] = new SomethingElse();    Constructor constructor =        yourClass.getConstructor(contstructorParamTypes);    Object instance = constructor.newInstance(constructorParams);}
It depends on one thing: if your class already resides in the classpath of your running application, or not; If the former, RayNbow's approach is the way to go, it works just fine, using what's called "reflection". If the latter is the case, you will need a custom class loader, usually a URLClassLoader. That is how you would add plugin jars on the fly to your application, for example.

So, if your maps are stored "outside" the loaded classpath of your program, you would have to load the classes manually using the URLClassLoader:

    /**     *     */    private static URLClassLoader createClassLoader() {        URL[] urls = null;        try {                        File dir = new File(DIRECTORY);            String[] files = dir.list(new JARFilenameFilter());                        urls = new URL[ files.length ];            for (int x = 0; x < files.length; x++) {                File file = new File(DIRECTORY + files[x]);                urls[x] = file.toURL();            }                    } catch (Exception e) {            e.printStackTrace();        }        return new URLClassLoader(urls);    }        /**     * FilenameFilter used for a JAR file     */    private static final class JARFilenameFilter implements FilenameFilter {        public boolean accept(File file, String str) {            return ( (!file.isDirectory()) || str.endsWith(".jar"));        }    }


Son Of Cain
a.k.a javabeats at yahoo.ca

This topic is closed to new replies.

Advertisement