通过它的简单名称反思地找到一个类 [英] Finding a class reflectively by its simple-name alone

查看:114
本文介绍了通过它的简单名称反思地找到一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何给定的函数允许我内省一个类,而不必编写包含类的包。



例如,想要查看类 Integer 的方法和超类,为此我必须指定类所在的包。这将是java.lang.Integer



而不是这样做,我想只是键入类名,以便显示类的信息。就像这个整数



如何让我的程序只检查类名,无论它位于何处?


< Java不会阻止您创建自己的 my.company.Integer 类和 my.other.company.Integer 类,因此如何不知道 Integer 类是 right



我可以建议的关闭的事情是创建一个预定义的包的列表,你想搜索的类,并继续尝试每个,直到你找到你的班。



如下:

  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] +。名称);
} catch(ClassNotFoundException e){
//不在这个包中,尝试另一个
} catch(...){
//处理其他问题...
}
}
//找不到:return null or throw ClassNotFoundException
return null;
}
}



如果您想获得所有可用包的列表而不是硬编码,见这里



请注意,此方法不太可能执行得很好,请谨慎使用。


I was wondering if there is any given function that allows me to introspect a class without having to write the packages where the class is contained.

For example, I want to take a look at the methods and superclasses of the class Integer in order to do that I have to specify the packages where the class is located. This will be "java.lang.Integer"

Instead of doing that I want to just type the class name in order to have the information of the class displayed. Just like this "Integer"

How can I make that my program just check the class name, no matter where is it located?

解决方案

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.

这篇关于通过它的简单名称反思地找到一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆