用byte[] 构造的Class 在 instanceof操作....



public class Untitled1
{
private final DirectLoader classLoader = new DirectLoader();

private static class DirectLoader extends ClassLoader
{
private DirectLoader()
{
super(ClassWork.class.getClassLoader());
}

private Class load(String name , byte[] data)
{
return super.defineClass(name , data , 0 , data.length);
}
}

public Class loadClass(String className)
{
try {
byte[] bytes = getBytes("classes/demo/WFProcess.class");
System.out.println("size=" + bytes.length);
return classLoader.load(className , bytes);
}
catch(Exception ex) {
throw new RuntimeException(ex);
}
}

private byte[] getBytes(String filename) throws IOException
{
File file = new File(filename);
long len = file.length();

byte raw[] = new byte[(int)len];

FileInputStream fin = new FileInputStream(file);

int r = fin.read(raw);
if(r != len) {
throw new IOException("Can't read all, " + r + " != " + len);
}

fin.close();
return raw;
}

public static void main(String[] args)
{
try {
Untitled1 u = new Untitled1();
Class clas = u.loadClass("demo.WFProcess");
Object o = clas.newInstance();
System.out.println("class=" + o.getClass());
if(o instanceof WFProcess) {
System.out.println("WFProcess");
}
if(o instanceof Cloneable) {
System.out.println("Cloneable");
}
System.out.println("OK");
}
catch(Exception ex) {
ex.printStackTrace();
}

}

}

public final class WFProcess implements Cloneable
{
private int id = -1;

private String name;

private String description;

private String attributes;

private boolean valid;

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public String getDescription()
{
return description;
}

public void setDescription(String description)
{
this.description = description;
}

public String getAttributes()
{
return attributes;
}

public void setAttributes(String attributes)
{
this.attributes = attributes;
}

public boolean getValid()
{
return valid;
}

public void setValid(boolean valid)
{
this.valid = valid;
}

public void test()
{
this.setId(2);
this.setAttributes("cc");
Object o=new Object();
}

}

大家的运行结果是什么?为什么只打印出 Cloneable

自己顶

怎么没人理我.jdon人气不如以前了.banq想想办法呀

这可能与虚拟机的编译规则有关,关注中。。。

因为是两个classloader的加载的WFProcess.class阿,
你把Class clas = u.loadClass("demo.WFProcess");这个clas变量和WFProcess.class比较一下,他们应该是不一样的
自然也就instanceof =false

这个问题我也遇到过,就是它只认得它的接口,不认识它本人,我在


Object o = clas.newInstance();

之后,

WFProcess w=(WFProcess)o;

发现不可以强制转换,但是我查看o的值时发现它的类型就是 WFProcess,


Class clas=Class.forName(WFProcess.class.getName());
WFProcess w=(WFProcess)clas.newInstance();

是完全可以的。


Class cls=ClassLoader.load(WFProcess.class.getName());
Object o1=cls.getInstance();


Class clas=Class.forName(WFProcess.class.getName());
Object o2=clas.newInstance();

不知道Object对象o1和对象o2有什么区别

不好意思,倒数第四行写错了,是


Object o1=clas.newInstance();

哦,明白了,谢谢

如果是2个不同的classloader,那为什么instanceof Cloneable可以呢?Cloneable也是由系统默认classloader加载的呀。