当前页面: 开发资料首页 → Java 专题 → 利用反射进行方法调用
利用反射进行方法调用
摘要: 利用反射进行方法调用
</td>
</tr>
<tr>
<td width="528" height="35" valign="top" class="ArticleTeitle"> import java.lang.reflect.*;
class Ref{
int i=0;
public Ref(){}
public Ref(int i){
this.i=i;
}
public int add(int n,int m){
return n+m;
}
}
public class RefTest{
public static void main(String args[]){
Ref re=new Ref();//实例化对象
System.out.println(re.i);
//利用反射设置实例变量的值
try{
Field field = Ref.class.getDeclaredField("i");
int value = field.getInt(re) + 10;
field.setInt(re, value);
}
catch (Exception ex) {
System.out.println("Error using reflection");
}
System.out.println(re.i);
//利用反射调用对象的方法
try {
Method method = Ref.class.getMethod("add", new Class [] { int.class,int.class });
Object[] arg ={new Integer(1),new Integer(2)};
Object value = new Integer(0);
value=method.invoke(re, arg);//注意返回类型
System.out.println("add(1,2)="+((Integer)value).intValue());
}catch (Exception ex) {
System.out.println("Error using reflection");
}
}
}
程序运行结果:
C:\java>java RefTest
0
10
add(1,2)=3
function TempSave(ElementID)
{
CommentsPersistDiv.setAttribute("CommentContent",document.getElementById(ElementID).value);
CommentsPersistDiv.save("CommentXMLStore");
}
function Restore(ElementID)
{
CommentsPersistDiv.load("CommentXMLStore");
document.getElementById(ElementID).value=CommentsPersistDiv.getAttribute("CommentContent");
}
</td>
<td width="170" valign="top" class="ArticleTeitle">
</td>
</tr>
<tr>
<td height="25" colspan="2" valign="top" class="ArticleTeitle">
↑返回目录
前一篇: 线程池与工作队列
后一篇: 先进先出的队列