Creating an object from a dynamically generated class

I am currently trying to achieve something similar: Based on this class, I am trying to create a new instance of the Class <? extends AbstractValidator> returned by getValidator () method.

public abstract class AbstractEnumDefinition
       extends AbstractRequestFieldDefinition {

    private Vector<String> values = new Vector<String>();

    public abstract void define(String lang);

    protected void addEnumDefinition(String value){

    public Vector<String> getValues(){
        return values;

    public Class<? extends AbstractValidator> getValidator() {
        return new AbstractValidator() {
            public boolean isValid(String value) {
                return values.contains(value);

            public String getDefaultValue() {
                return "";


Let's say I create this class:

public class LanguageDefinition extends AbstractEnumDefinition {

    public LanguageDefinition() {

    public void define(String language) {


Later in my code I call

new LanguageDefinition().getValidator().getConstructor().newInstance()


The class I'm trying to create here is not declared anywhere, but "dynamically generated" / "dynamically created" in the AbstractEnumDefinition class.

When I try to do this, I get java.lang.InstantiationException




I assume this is because this class must be explicitly created beforehand and not dynamically specified?

Is there some solution that would allow me not to write one class for the validator?

Thanks for the help,



source to share

2 answers

I can only make guesses since I don't see the code where you actually use the class, but you should check:

One thing mentioned is the instantiation error since the class is an abstract class (perfectly logical since you cannot create abstract classes).

Also, I don't understand why you need to return the class and then create the object as well. Why not just define the Validator interface and return your Validator method.



This doesn't work for anonymous classes, as far as I know you need to convert your class to a named inner class:

But even that won't work, because you might not have a default constructor. Inner classes receive implicit constructor arguments to maintain a reference to the enclosing class. Unfortunately, Closures doesn't work that well in static languages.

In general, inner non-classical classes cannot be instantiated outside an instance of the enclosing class.



All Articles