list - Java calling method from generic class -
is possible.
list<?> mylist = getmylist(); class cls = class.forname("com.lab.myclass"); cls = mylist.get(0); cls.getvalue();
create instance fully-qualified name of class , use declared methods?
no, if call class.forname
, @ compile time know nothing returned class
instance. don't know represents class; might interface example. in particular, if class , create instance of it, cannot call methods of except defined in object
because, @ compile time, compiler cannot check whether these methods exist.
the 2 solutions:
first, can use reflection find out methods class has, , call these methods. cumbersome.
second, if use class.forname
dynamically load classes @ runtime, know classes load. example, might know class implements interface. can cast result of newinstance
interface , call methods defined in interface directly.
for example:
// in file plugin.java interface plugin { void dosomething(); } // in file main.java public class main { ... void runplugin() { try { class<?> pluginclass = class.forname("pkg.name.myplugin"); plugin plugin = (plugin) pluginclass.newinstance(); plugin.dosomething(); } catch (...) { // catch necessary exceptions } } }
Comments
Post a Comment