当前位置: 技术问答>java相关
如何使用利用RTTI创建的对象实例??
来源: 互联网 发布时间:2015-08-26
本文导语: 例如: String className = new String("A"); Class c = null; try { c = Class.forName(className); } catch (ClassNotFoundException e){} Object o = null; try { ...
例如:
String className = new String("A");
Class c = null;
try {
c = Class.forName(className);
}
catch (ClassNotFoundException e){}
Object o = null;
try {
o =c.newInstance();
}
catch (InstantiationException e){}
接着我如果想使用o,例如,调用其一个方法,该如何进行操作呢?
Java有没有提供一种方法可以让我们在创建该实例的时候,选用非缺省的构建器方法从而达到给该实例赋值的目的呢?
请高手不吝指教!
thanks in advance!
String className = new String("A");
Class c = null;
try {
c = Class.forName(className);
}
catch (ClassNotFoundException e){}
Object o = null;
try {
o =c.newInstance();
}
catch (InstantiationException e){}
接着我如果想使用o,例如,调用其一个方法,该如何进行操作呢?
Java有没有提供一种方法可以让我们在创建该实例的时候,选用非缺省的构建器方法从而达到给该实例赋值的目的呢?
请高手不吝指教!
thanks in advance!
|
Method cMethod = c.getMethod(strMethodName, new java.lang.Class[]{parameterTypesClass});
cMethod.invoke(o, new Object[]{parameter});
搞定!
cMethod.invoke(o, new Object[]{parameter});
搞定!
|
import java.lang.reflect.*;
public class ShowMethods {
static final String usage =
"usage: n" +
"ShowMethods qualified.class.namen" +
"To show all methods in class or: n" +
"ShowMethods qualified.class.name wordn" +
"To search for methods involving 'word'";
public static void main(String[] args) {
if(args.length
public class ShowMethods {
static final String usage =
"usage: n" +
"ShowMethods qualified.class.namen" +
"To show all methods in class or: n" +
"ShowMethods qualified.class.name wordn" +
"To search for methods involving 'word'";
public static void main(String[] args) {
if(args.length