Java: properly checked class instantiation using reflection -


i'm trying use 1 of simplest forms of reflection create instance of class:

package some.common.prefix;  public interface {     void configure(...);     void process(...); }  public class myexample implements {     ... // proper implementation }  string myclassname = "myexample"; // read external file in reality  class<? extends my> myclass =     (class<? extends my>) class.forname("some.common.prefix." + myclassname); my = myclass.newinstance(); 

typecasting unknown class object we've got class.forname yields warning:

type safety: unchecked cast class<capture#1-of ?> class<? extends my>

i've tried using instanceof check approach:

class<?> loadedclass = class.forname("some.common.prefix." + myclassname); if (myclass instanceof class<? extends rst>) {     class<? extends my> myclass = (class<? extends my>) loadedclass;     my = myclass.newinstance(); } else {     throw ... // awful exception } 

but yields compilation error: cannot perform instanceof check against parameterized type class<? extends my>. use form class<?> instead since further generic type information erased @ runtime. guess can't use instanceof approach.

how rid of , how supposed properly? possible use reflection without these warnings @ (i.e. without ignoring or supressing them)?

this how it:

/**  * create new instance of given class.  *   * @param <t>  *            target type  * @param type  *            target type  * @param classname  *            class create instance of  * @return new instance  * @throws classnotfoundexception  * @throws illegalaccessexception  * @throws instantiationexception  */ public static <t> t newinstance(class<? extends t> type, string classname) throws         classnotfoundexception,         instantiationexception,         illegalaccessexception {     class<?> clazz = class.forname(classname);     class<? extends t> targetclass = clazz.assubclass(type);     t result = targetclass.newinstance();     return result; }   my = newinstance(my.class, "some.common.prefix.myclass"); 

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -