代码之家  ›  专栏  ›  技术社区  ›  Ritwik Bose

外部检查Java对象层次结构

  •  0
  • Ritwik Bose  · 技术社区  · 15 年前

    假设我有一个字符串“bar”,我想知道bar是否是一个有效的对象,更进一步地说,“bar”是否扩展了“foo”。我会使用Java反射还是有更好的方法,比如数据库?我该怎么做?

    干杯

    2 回复  |  直到 11 年前
        1
  •  1
  •   Bozho    15 年前

    如果您不知道包——只有类名,可以使用Spring框架来尝试:

    List<Class> classes = new LinkedList<Class>();
    PathMatchingResourcePatternResolver scanner = new 
        PathMatchingResourcePatternResolver();
    // this should match the package and the class name. for example "*.Bar"
    Resource[] resources = scanner.getResources(matchPattern); 
    
    for (Resource resource : resources) {
        Class<?> clazz = getClassFromFileSystemResource(resource);
        classes.add(clazz);
    }
    
    
    public static Class getClassFromFileSystemResource(Resource resource) throws Exception {
        String resourceUri = resource.getURI().toString();
        // finding the fully qualified name of the class
        String classpathToResource = resourceUri.substring(resourceUri
                .indexOf("com"), resourceUri.indexOf(".class"));
        classpathToResource = classpathToResource.replace("/", ".");
        return Class.forName(classpathToResource);
    }
    

    上面的两个方法为您提供了名为“bar”的类的列表(它们可能不止一个!).

    那就更容易了

    expectedSuperclass.isAssignableFrom(yourClass);
    
        2
  •  1
  •   David Rabinowitz    15 年前

    是的,思考就是答案:

    Class barClass = Class.forName("some.package.Bar"); // will throw a ClassNotFoundException if Bar is not a valid class name
    Class fooClass = some.package.Foo.class;
    assert fooClass.isAssignableFrom(barClass); // true means Bar extends (or implements) Foo