JAVA通过反映方法实现C#的委托

来源:互联网 发布:使用u盘安装ubuntu 编辑:程序博客网 时间:2024/05/21 07:53

C#委托实现了类内部的方法暴露给调用者,类似C++中的方法指针,方法以返回值的形式传递。这种设计方式可以实现统一方法名。

Java代码 复制代码 收藏代码
  1. import java.util.*;
  2. import java.lang.reflect.*;
  3. interface Command {
  4. Method executeMethod();
  5. }
  6. class StartComputer implements Command {
  7. Class classType = StartComputer.class;
  8. public Method executeMethod() {
  9. try {
  10. return classType.getMethod("innerMethod",new Class[]{ int.class });
  11. } catch(NoSuchMethodException e) {
  12. e.printStackTrace();
  13. return null;
  14. }
  15. }
  16. public void innerMethod(int param) {
  17. // TODO: something.
  18. System.out.println("----------------- OUTPUT ------------------");
  19. System.out.println(param);
  20. }
  21. }
  22. public class CommandStudy {
  23. public static Map<String, Class> commandMap =new HashMap<String, Class>();
  24. static {
  25. commandMap.put("StartComputer", StartComputer.class);
  26. }
  27. public static void main(String[] args) throws IllegalAccessException, InstantiationException , InvocationTargetException{
  28. Class startComputerClass = commandMap.get("StartComputer");
  29. Command someCommand = (Command)startComputerClass.newInstance();
  30. Method executeMethod = someCommand.executeMethod();
  31. executeMethod.invoke(someCommand, new Object[] {new Integer(200) });
  32. }
  33. }

Command类是公共接口类,对外开放的接口方法。StartCommand实现一个Command接口。在StartCommand的executeMethod方法的内部实现了方法的转移,把StartCommand里其它方法转移到接口方法executeMethod里,这样设计后,统一方法接口。

C#中委托对象delegate与JAVA中Method对象主要区别在于delegate里包含方法的对象,而Method主要是对方法的描述,不包含任务对象信息。

JAVA中用invoke方法时可能会产生大量的异常。