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.
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);
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.
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.
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./
}
}