Java Reflection without qualified name

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

提交回复
热议问题