日期:2014-05-20  浏览次数:20905 次

如何判断一个jar包中的一些class是否implements或者extends于某个基类
系统中有个基类接口例如AType.class,那么如果有个BType   implements   AType,那么只要用if   instanceof来判断就行了。

现在问题是,用户开发了一个CType   implements   AType,然后编译做成一个.jar包了,作为一个文件传了过来,我用流的方式读进了这个文件,那么我该怎么做才能知道这个.jar包中的这个CType.class是否是instanceof   AType?

------解决方案--------------------
是不是我智商太低了
作成.JAR包 然后用file读取(OR 放入流中传输)意义何在(难道 LZ您制作成JAR只是为了压缩 那您直接如何判断 压缩包中文件比较清楚些吧)请LZ明示
我制作的jar不是用于classpath 就是加入到 web-inf/lib下了 没试过用i/o读取(sorry智商低玩不了有创意东西)

还有LZ
我考虑您把用户传的jar包 保存在您的classpath里(web-inf/lib下)这样您的服务器设置为支持类的动态加载,这样就可以使用您不屑的反射了

用户传给您个jar包 是处于什么考虑的呢? 这个jar包将怎么用呢?望LZ不吝赐教

LZ我欠你什么吗?做人要厚道
------解决方案--------------------
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class Test {
  public static void main(String[] args) throws IOException,
      InstantiationException, IllegalAccessException {

    JarFile jar = new JarFile( "Java2Demo.jar ");
    JarEntry entry = jar.getJarEntry( "java2d/DemoFonts.class ");
    
    InputStream is = jar.getInputStream(entry);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    int r=0;
    while((r=is.read())!=-1) {
      bao.write(r);
    }
    byte[] b = bao.toByteArray();
    
    MyClassLoader cl = new MyClassLoader(b);
    Class c = cl.findClass(entry.getName().replace( "/ ", ". ").replace( ".class ", " "));

    Object obj = c.newInstance();
    System.out.println(obj instanceof Runnable);

    is.close();
    jar.close();
  }
}

class MyClassLoader extends ClassLoader {
  private byte[] b;
  public MyClassLoader(byte[] b) {
    this.b = b;
  }
public Class <?> findClass(String name) {
return defineClass(name, b, 0, b.length);
}
}