Java Reflection without qualified name

后端 未结 4 1810
时光取名叫无心
时光取名叫无心 2020-12-21 17:48

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

I want to pass in the className without specifying the package n

相关标签:
4条回答
  • 2020-12-21 18:19
    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./  
        }
    }
    
    0 讨论(0)
  • 2020-12-21 18:36

    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);
    
    0 讨论(0)
  • 2020-12-21 18:36

    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.
    
    0 讨论(0)
  • 2020-12-21 18:37

    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.

    0 讨论(0)
提交回复
热议问题