I have a problem definition where I need to create Class type and add fields, methods to it at runtime in Java. Once I have Class object of particular class type, I can create instance of that class.
Mainly I am not allowed to make any bytecode alterations or disk operations. Simply need to do in-memory operation.
I also tried extending java.lang.ClassLoader and provide my own implementation of defineClass(). But this method is final so can not override it.
Tried below code but did not help:
public class MethodParameterSpy {
public static class MyClassLoader extends ClassLoader{
public Class loadClass(String name) throws ClassNotFoundException {
return defineClass("MyObject","public class Demo{ int i; }".getBytes(), 0,"public class Demo{}".getBytes().length+1);
}
}
public static void main(String... args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
ClassLoader clloader=new MethodParameterSpy.MyClassLoader();
Class c=clloader.loadClass(null);
System.out.println(c);
}
}
Exception in thread "main" java.lang.ClassFormatError: Incompatible magic value 1886741100 in class file MyObject
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at MethodParameterSpy$MyClassLoader.loadClass(MethodParameterSpy.java:71)
at MethodParameterSpy.main(MethodParameterSpy.java:78)