函数名是拼接得到的,怎样运行这个函数?

rubber365 2003-06-01 11:21:01
比如
out.println(spb.teststr());
输出:
bbbb


tempstr="spb.teststr()";
out.println(tempstr);
输出却是:
spb.teststr()

有什么好的解决办法呢?
...全文
179 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
asdmonster 2003-06-01
  • 打赏
  • 举报
回复
//用 反射,下面是示例代码。

package mytest;

import java.lang.reflect.*;
import java.lang.*;

public class ReflectTest {

private String str;

public void setStr( String theStr){ this.str = theStr;}

public String getStr(){ return this.str;}

public ReflectTest() {}
public ReflectTest( String theStr){ this.str = theStr;}

public void printStr(){
System.out.println(" invoke this method start");
System.out.println(" theStr ="+this.str);
System.out.println(" this invoke is end");
}

public static void main(String[] args) {
ReflectTest reflectTest1 = new ReflectTest( " aaa");
Class reflectClass = reflectTest1.getClass();
// that is your request:

try {
Method theSpecialMethod = reflectClass.getMethod("printStr",null);
Object theSpecialRerurnValue = theSpecialMethod.invoke( reflectTest1,null);
System.out.println(" theSpecialRerurnValue = "+ theSpecialRerurnValue);
}
catch (IllegalAccessException ex) {
ex.printStackTrace();
}catch (IllegalArgumentException ex) {
ex.printStackTrace();
}catch (InvocationTargetException ex) {
ex.printStackTrace();
}catch (NoSuchMethodException ex) {
ex.printStackTrace();
}catch (SecurityException ex) {
ex.printStackTrace();
}
}



asdmonster 2003-06-01
  • 打赏
  • 举报
回复
aa

67,512

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧