From d5ba7412cd10324d65af93c98830d34e0a202bb8 Mon Sep 17 00:00:00 2001 From: Joel Dice Date: Sat, 15 Jan 2011 10:33:56 -0700 Subject: [PATCH] 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. --- test/DefineClass.java | 48 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 41 insertions(+), 7 deletions(-) diff --git a/test/DefineClass.java b/test/DefineClass.java index bfbf67b0cd..0b72cd5b95 100644 --- a/test/DefineClass.java +++ b/test/DefineClass.java @@ -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; + } + } }