0

How can I dynamically create a class in Java, if I only now the parent class at runtime via reflection?

// I only know what ParentClass is at runtime
// but I know that ParentClass implements SomeInterface.
public class MyClass extends ParentClass implements SomeInterface {
    // I know the method I want to override,
    // and that ParentClass has a no-argument constructor.
    @Override
    public int method(int arg) {
        return 42 * arg;
    }
}

E.g. in Python you could use

MyClass = type("MyClass", (ParentClass,), {
    'method': lambda self, arg: 42 * arg
})
# or even easier
class MyClass(ParentClass):
    def name(self, arg):
        return 42 * arg

So, is there an equivalent to Python's type(name, bases, dict) in Java?

Kijewski
  • 25,517
  • 12
  • 101
  • 143

1 Answers1

1

There is no direct/easy way to do this in java. We need to create class file and load it to classloader. You can refer the following answer Writing and implementing new Java class files during run-time. Several third party libraries like ASM, CGLIB, JAVASSIST helps in creating code on the fly.

Community
  • 1
  • 1
Sangeeth
  • 614
  • 1
  • 5
  • 14