Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Sure there is. You need a java.lang.Class instance initially, for the target class you wish to create. Depending on your structure, this might either be passed in by a caller (if they're supplying the concrete class they want created), or you can statically access the class variable (e.g. <code>MyFooImpl.class</code>).</p> <p>The simplest way is to call <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#newInstance()" rel="nofollow noreferrer">Class.newInstance()</a>. This invokes the default, no-arg constructor (assuming there is one for the class; if not it throws an exception).</p> <p>If you need to invoke a particular constructor with some argument, you need to call <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getConstructor(java.lang.Class...)" rel="nofollow noreferrer">Class.getConstructor()</a> to get a Constructor instance, which you can then call <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Constructor.html#newInstance(java.lang.Object...)" rel="nofollow noreferrer">newInstance</a> on.</p> <p>In all cases you'll need to deal with reflection exceptions that you wouldn't get if invoking the constructor directly.</p> <p><strong>Big edit</strong>: I assume your question was about creating instances of a class via reflection. However I'm beginning to think that you're asking about <em>defining</em> new classes through at runtime. If so, then reflection won't help you here - you'd need to invoke a compiler programatically, which I believe can be done but I'm not 100% on the details. I think you'd also have to go through some hoops to get the ClassLoader to pick up your new class too.</p>
 

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