Java will not stop you from creating your own my.company.Integer
class and my.other.company.Integer
class, so how it cannot know which Integer
class is the right one.
The closes thing to an answer I can suggest is to create a pre-defined list of packages where you want to search the class for, and keep trying each until you find your class.
So something like:
class ClassFinder{
public static final String[] searchPackages = {
"java.lang",
"java.util",
"my.company",
"my.company.other" };
public Class<?> findClassByName(String name) {
for(int i=0; i<searchPackages.length; i++){
try{
return Class.forName(searchPackages[i] + "." + name);
} catch (ClassNotFoundException e){
//not in this package, try another
} catch (...){
//deal with other problems...
}
}
//nothing found: return null or throw ClassNotFoundException
return null;
}
}
If you want to get a list of all available packages instead of hard-coding them, see here.
Be warned that this method is unlikely to perform very well, so use it sparingly.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…