简体   繁体   中英

Reflection getDeclaredMethods() and class that is not in classpath

I am using reflection to get all methods from a specific class.

This class has references to class that not in my class path so I get an exception:

java.lang.NoClassDefFoundError:

On this:

Method methods[] = theClass.getDeclaredMethods();

Is it possible, somehow,to "skip" everything that is not in classpath?

Class.forName() will not load a class, whether it is or isn't in the classpath. It will only return a handle to a class that is already loaded.

A class gets loaded in one of 2 main ways:

1.)The class is referenced in the import statements(java.lang.* is imported automatically so every class in java.lang package is class-loaded from the start)

2.)A class is loaded using a call from a ClassLoader, in which case all of its dependencies are resolved. and loaded as well

So if you are trying to load a class outside of the classpath, or with dependencies outside the classpath, you need to subclass ClassLoader and tell it how to load your classes and their dependencies.

See ClassLoader specification here: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/ClassLoader.html

Also, there are ready made subclasses of ClassLoader that may do what you want such as URL ClassLoader which will let you simply point the ClassLoader instance at the path, and load any classes in that path.

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