Note that there are some explanatory texts on larger screens.

plurals
  1. POInstantiate an object from a dynamically generated class
    primarykey
    data
    text
    <p>I am currently trying to achieve something like this: Based on this class, I try to create a new instance of the class Class&lt;? extends AbstractValidator> returned by the method getValidator().</p> <pre><code>public abstract class AbstractEnumDefinition extends AbstractRequestFieldDefinition { private Vector&lt;String&gt; values = new Vector&lt;String&gt;(); public abstract void define(String lang); protected void addEnumDefinition(String value){ values.add(value); } public Vector&lt;String&gt; getValues(){ return values; } @Override public Class&lt;? extends AbstractValidator&gt; getValidator() { return new AbstractValidator() { @Override public boolean isValid(String value) { return values.contains(value); } @Override public String getDefaultValue() { return ""; } }.getClass(); } } </code></pre> <p>Say I create this class:</p> <pre><code>public class LanguageDefinition extends AbstractEnumDefinition { public LanguageDefinition() { super(); } @Override public void define(String language) { addEnumDefinition("BEL-fr"); addEnumDefinition("BEL-nl"); addEnumDefinition("BEL-en"); } } </code></pre> <p>Later in my code, I call</p> <pre><code>new LanguageDefinition().getValidator().getConstructor().newInstance() </code></pre> <p>The class I am trying to instantiate here is not declared anywhere, but "generated dynamically"/"dynamically created" within the AbstractEnumDefinition class.</p> <p>When trying to do this, I get an <code>java.lang.InstantiationException</code> for </p> <pre><code>be....servlets.model.extraction.filter.editor.AbstractEnumDefinition$1 </code></pre> <p>I guess this is due to the fact that this Class has to be explicitly created before hand, and not referenced dynamically?</p> <p>Is there some kind of solution that would allow me to not have to write one class per validator?</p> <p>Thanks for the help,</p> <p>Eric</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload