help needed in creating new class from scratch
neuralnet May 9, 2005 3:39 PMI am attempting to use the following code to create a new class from scratch and call its method.
import java.lang.reflect.Method;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.Loader;
import javassist.Modifier;
public class Main {
public static void main( String[] args ) throws Throwable {
Main main = new Main( );
main.run( args );
} // end main( )
protected void run( String[] args ) throws Throwable {
try {
ClassPool classPool = ClassPool.getDefault( );
CtClass helloWorldClass = classPool.makeClass( "HelloWorld" );
CtMethod method = CtNewMethod.make(
Modifier.PUBLIC,
CtClass.voidType,
"doRun",
new CtClass[] { },
new CtClass[] { },
"{ System.out.println( \"hello, world, hello\" ); }",
helloWorldClass );
helloWorldClass.addMethod( method );
Class helloWorld = helloWorldClass.toClass( );
System.out.println( "class: " + helloWorld );
Method runMethod = helloWorld.getDeclaredMethod( "doRun", new Class[] { } );
System.out.println( "method: " + runMethod );
System.out.println( "declaring class: " + runMethod.getDeclaringClass( ) );
System.out.println( "class comparision: " + helloWorld.equals( runMethod.getDeclaringClass( ) ) );
System.out.println( "parameter types: " + runMethod.getParameterTypes( ).length );
System.out.println( "return type: " + runMethod.getReturnType( ) );
runMethod.invoke( helloWorld, new Object[] { } );
} catch ( Exception e ) {
e.printStackTrace( );
}
} // end run( )
} // end class Main
I am experiencing the following error:
class: class HelloWorld
java.lang.IllegalArgumentException: object is not an instance of declaring class
method: public void HelloWorld.doRun()
declaring class: class HelloWorld
class comparision: true
parameter types: 0
return type: void
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)
at Main.run(Main.java:39)
at Main.main(Main.java:14)
I'd appreciate any help in resolving the problem. Thanks,
neuralnet