update DefineClass to exercise Class.newInstance

This is an attempt to reproduce an issue reported on the discussion
group.  However, the current form of the test is passing, so further
work will be necessary to trigger the bug.
This commit is contained in:
Joel Dice 2011-01-15 10:33:56 -07:00
parent b6978c6c68
commit d5ba7412cd

View File

@ -3,15 +3,15 @@ import java.io.File;
import java.io.FileInputStream;
public class DefineClass {
private static File findHello(File directory) {
private static File findClass(String name, File directory) {
File[] files = directory.listFiles();
for (File file: directory.listFiles()) {
if (file.isFile()) {
if (file.getName().equals("Hello.class")) {
if (file.getName().equals(name + ".class")) {
return file;
}
} else if (file.isDirectory()) {
File result = findHello(file);
File result = findClass(name, file);
if (result != null) {
return result;
}
@ -33,11 +33,25 @@ public class DefineClass {
}
}
private static Class loadClass(String name) throws Exception {
return new MyClassLoader(DefineClass.class.getClassLoader()).defineClass
(name, read(findClass(name, new File(System.getProperty("user.dir")))));
}
private static void testStatic() throws Exception {
loadClass("DefineClass$Hello")
.getMethod("main", String[].class).invoke(null, (Object) new String[0]);
}
private static void testDerived() throws Exception {
System.out.println
(String.valueOf
(((Base) loadClass("DefineClass$Derived").newInstance()).zip()));
}
public static void main(String[] args) throws Exception {
byte[] bytes = read(findHello(new File(System.getProperty("user.dir"))));
Class c = new MyClassLoader(DefineClass.class.getClassLoader()).defineClass
("Hello", bytes);
c.getMethod("main", String[].class).invoke(null, (Object) new String[0]);
testStatic();
testDerived();
}
private static class MyClassLoader extends ClassLoader {
@ -49,4 +63,24 @@ public class DefineClass {
return super.defineClass(name, bytes, 0, bytes.length);
}
}
public static class Hello {
public static void main(String[] args) {
System.out.println("hello, world!");
}
}
public abstract static class Base {
public int foo;
public void bar() { }
public abstract int zip();
}
public static class Derived extends Base {
public int zip() {
return 42;
}
}
}