0

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)
Mukul Gupta
  • 2,310
  • 3
  • 24
  • 39
  • 3
    please share your code and what you have tried so far – Adi Ohana Jun 03 '19 at 09:50
  • 1
    Possibly related: [Creating classes dynamically with Java](https://stackoverflow.com/q/2320404) – Pshemo Jun 03 '19 at 09:58
  • Try java reflections – Nasreen Jun 03 '19 at 10:06
  • @Pshemo No this link does not answer my question. Thanks. – Sandip Patel Jun 03 '19 at 10:07
  • @NasreenMD I understand solution could be present in reflection API. I could not find any way to do it. Throughout reflection API, I need Class Type created for creating instance. But I need to create class type itself. – Sandip Patel Jun 03 '19 at 10:08
  • @SandipPatel, hope this helps - https://stackoverflow.com/questions/781805/defining-a-class-while-a-java-application-is-running – Nasreen Jun 03 '19 at 10:19
  • 2
    "I need to create Class type and add fields, methods to it at runtime in Java": it is unlikely that you really *need* to do this. You probably have a different problem, and you incorrectly *think* that would be the solution. – Raedwald Jun 03 '19 at 12:38

0 Answers0