Java Reflection without qualified name

2019-07-11 04:49发布

I am trying to do Java Reflection using Class c = Class.forName(className)

I want to pass in the className without specifying the package name as the String className will contain classes from multiple sub-packages say com.A.*,com.B.* .... com.Z.*

Is it possible?

It will not be feasible to do a case switch to pre-pend the different sub-packages if I have many sub-packages in this case.

4条回答
Summer. ? 凉城
2楼-- · 2019-07-11 05:05

One simple option would be to have a list of candidate packages:

for (String pkg : packages) {
    String fullyQualified = pkg + "." + className;
    try {
        return Class.forName(fullyQualified);
    } catch (ClassNotFoundException e) {
        // Oops. Try again with the next package
    }
}

This won't be the nicest code in the world, admittedly...

You may be able to make it faster by looking for alternative calls (e.g. ClassLoader.getResource) which don't throw exceptions if the class isn't found.

There's certainly nothing I'm aware of to allow you to find a class without specifying a name at all.

查看更多
时光不老,我们不散
3楼-- · 2019-07-11 05:10

First, get all classes with the Reflections library

 Reflections reflections = new Reflections();

 Set<Class<?>> allClasses = reflections.getSubTypesOf(Object.class);

Next, build up a lookup-map.

// Doesn't handle collisions (you might want to use a multimap such as http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html instead)
Map<String, Class<?>> classBySimpleName = new HashMap<>();

for(Class<?> c : allClasses) {
    classBySimpleName.put(c.getSimpleName(), c);         
}

When you need to lookup a class you'll do:

Class<?> clazz = classBySimpleName.get(className);
查看更多
神经病院院长
4楼-- · 2019-07-11 05:17
import com.bvs.copy.UserEffitrac;

public class TestCopy {
    public static void main(String[] args) {

     /* Make object of your choice ans assign it to
        Object class reference */
        Object obj = new UserEffitrac();

     /* Create a Class class object */
        Class c = obj.getClass();
   /* getSimpleName() gives UserEffitrac as output */
        System.out.println(c.getName());
        /*getName() or getConicalName() will give complete class name./  
    }
}
查看更多
成全新的幸福
5楼-- · 2019-07-11 05:22

From the javadoc of java.lang.Class its not possible

public static Class<?> forName(String className)
                    throws ClassNotFoundException

Parameters:
className - the fully qualified name of the desired class.
Returns:
the Class object for the class with the specified name.
查看更多
登录 后发表回答