【Java】反射初探(invoke)

来源:互联网 发布:java线程优先级原理 编辑:程序博客网 时间:2024/06/05 17:57

    最近做服务接口,由于时间比较紧,就在设计上比较取巧(其实也是偷懒),使用了反射机制。关键的设计是:使用者调用接口时,传递命令名称和参数,从而可以得到结果。更明确的说实现目的就是:知道方法(函数)名称和参数值,得到此方法的运行后的值。很明显就是方法反射。

   方法类Methods.java

public class Methods {public String one(String a, int b, boolean c) {//if c, hello this number;otherwise hello.if(c) {return a + " number " + b;}return a;}}
   反射测试类demo Test.java

public class Test {public static void main(String[] args) {String[] request = {"one", "hello", "1", "true"};//cmdMethods m = new Methods();Method[] methods = m.getClass().getMethods();Method method = null;for (Method temp : methods) {if(temp.getName().equals(request[0])) {method = temp;break;//if the class has many methods that have the same name, you need another treatment.}}Class<?>[] classes = method.getParameterTypes();//compare the number of parametersif(classes.length != request.length - 1) {//TODOreturn;}//compare the type of parameters Object[] params = new Object[classes.length];for (int i = 0; i < params.length; i++) {try {if(classes[i].equals(int.class)) {params[i] = Integer.parseInt(request[i+1]);} else if(classes[i].equals(boolean.class)) {params[i] = Boolean.parseBoolean(request[i+1]);} else {params[i] = classes[i].cast(request[i+1]);}} catch (NumberFormatException e) {// TODO: handle exception} catch (ClassCastException e) {// TODO: handle exception}}String str = "";try {str = (String) method.invoke(m, params);} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(str);}}




原创粉丝点击