Java Reflection without qualified name

后端 未结 4 1809
时光取名叫无心
时光取名叫无心 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:36

    First, get all classes with the Reflections library

     Reflections reflections = new Reflections();
    
     Set> 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> 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);
    

提交回复
热议问题