利用java反射调用实现对字符串的解析,成功调入函数,并且返回值

第一步:首先定位类简写与完整类名的映射

    public static Properties relectProperties;
    static {
        relectProperties = new Properties();
        InputStream in = ReflectUtils.class.getResourceAsStream("reflect.properties");
        try {
            relectProperties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
    
    public static String getRealName(String name) {
        String real = relectProperties.getProperty(name);
        if(real != null && real.length() > 0) {
            return real;
        }
        return name;
    }

  把文件的映射读进来

DoSocket=com.test.DoSocket
GetSocketTest=com.test.GetSocketTest
Test=com.test.Test

2.通过字符串进行调用。

  1     public static Object invoke(String content) {
  2         String name = null;
  3         String left = null;
  4         try {
  5             if(content == null || content.trim().length() == 0) {
  6                 return null;
  7             }
  8             content = content.trim();
  9             if(content.indexOf(".") >= 0) {
 10                 name = content.substring(0, content.indexOf("."));
 11                 left = content.substring(content.indexOf(".") + 1);
 12             } else {
 13                 name = content;
 14                 left = null;
 15             }
 16             name = getRealName(name);
 17             Class myClass = Class.forName(name);
 18             if(left == null) {
 19                 return getFunctionAndPublicMethod(myClass);
 20             } else {
 21                 return invokeAny(content);
 22             }
 23         } catch (Exception e) {
 24             if(name == null) {
 25                 System.err.println("未能正确的获取类名");
 26             }
 27             //e.printStackTrace();
 28         }
 29         return null;
 30     }
 31     
 32     
 33     private static Object invokeAny(String content) {
 34         String name = null;
 35         String left = null;
 36         try {
 37             content = content.trim();
 38             if(content.indexOf(".") >= 0) {
 39                 name = content.substring(0, content.indexOf("."));
 40                 left = content.substring(content.indexOf(".") + 1);
 41             } else {
 42                 return content;
 43             }
 44             name = getRealName(name);
 45             Class myClass = Class.forName(name);
 46             if(left == null) {
 47                 return name;
 48             } else {
 49                 String function = null;
 50                 ArrayList<Object> args = new ArrayList<Object>();
 51                 if(left.contains("(") && left.contains(")")) {
 52                     int bracketLeft = left.indexOf("(");
 53                     int bracketRight = left.indexOf(")");
 54                     function = left.substring(0, left.indexOf("("));
 55                     left = left.substring(left.indexOf("(") + 1);
 56                     
 57                     while (left.contains(",")) {
 58                         int nextBracketLeft = left.indexOf("(");
 59                         int nextBracketRight = left.indexOf(")");
 60                         int nextComma = left.indexOf(",");
 61                         if(nextComma < nextBracketRight && nextBracketLeft != -1 && nextBracketLeft < nextBracketRight) {
 62                             String invokeString = left.substring(0, nextBracketRight +1);
 63                             args.add(invokeAny(invokeString));
 64                             left = left.substring(nextBracketRight + 1); 
 65 //                            String invokeString = left.substring(0, nextComma);
 66 //                            args.add(invokeAny(invokeString));
 67 //                            left = left.substring(nextComma + 1); 
 68                         } else if(nextComma < nextBracketRight && nextBracketLeft == -1) {
 69                               String invokeString = left.substring(0, nextComma);
 70                               args.add(invokeAny(invokeString));
 71                               left = left.substring(nextComma + 1); 
 72                         } else if(nextBracketRight < nextComma && nextBracketLeft != -1) {
 73                             String invokeString = left.substring(0, nextBracketRight + 1);
 74                             args.add(invokeAny(invokeString));
 75                             left = left.substring(nextComma + 1); 
 76                       } else {
 77                             System.err.println("表达示不正确");
 78                             throw new Exception("表达示不正确");
 79                         }
 80                     }
 81                     if(!left.contains(")")) {
 82                         System.err.println("缺少右括号,请检查完整性");
 83                         throw new Exception("缺少右括号,请检查完整性");
 84                     }
 85                     String last = left.substring(0, left.indexOf(")"));
 86                     if(last.trim().length() > 0) {
 87                         args.add(invokeAny(last));
 88                     }
 89                     return invokeFunction(null, myClass, function, args);
 90                 } else {
 91                     System.err.println("未能正确匹配括号");
 92                 }
 93                 
 94             }
 95         } catch (Exception e) {
 96             if(name == null) {
 97                 System.err.println("未能正确的获取类名");
 98             }
 99             e.printStackTrace();
100         }
101         return null;
102     }
103     
104     public static void match(StringBuilder result, Class myClass, String left) {
105         String function = null;
106         String[] args = null;
107         if(left.contains("(") && left.contains(")")) {
108             function = left.substring(0, left.indexOf("("));
109             left = left.substring(left.indexOf("(") + 1);
110             String arg = left.substring(0, left.indexOf(")"));
111             args = arg.split(",");
112         } else {
113             System.err.println("未能正确匹配括号");
114         }
115     }
116     
117     private static ArrayList<Method> getMethods(Class myClass, String function) {
118         ArrayList<Method> result = new ArrayList<Method>();
119         Method[] methods = myClass.getMethods();
120         for(Method method : methods) {
121             if(method.getName().equals(function)) {
122                 result.add(method);
123             }
124         }
125         return result;
126     }
127     
128     private static Object invokeFunction(StringBuilder result, Class myClass, String function, ArrayList<Object> args) {
129         ArrayList<Method> methods = getMethods(myClass, function);
130         try {
131             for(Method method : methods) {
132                 Class[] paras = method.getParameterTypes();
133                 if(paras.length != args.size()) {
134                     continue;
135                 }
136                 return method.invoke(null, toObjects(paras, args));
137             }
138         } catch (Exception e) {
139         }
140         System.err.println("未发现匹配的函数,请检查函数的正确性");
141         return null;
142     }
143     
144     private static Object[] toObjects(Class[] paras, ArrayList<Object> args) {
145         Object[] objects = new Object[paras.length];
146         for(int i = 0; i < paras.length; i++) {
147             objects[i] = trave(paras[i], args.get(i));
148         }
149         return objects;
150     }
151     
152     public static Object trave(Class destClass, Object value) {
153         if(value == null || destClass == null) {
154             return value;
155         }
156         try {
157             if(destClass.equals(int.class) || destClass.equals(Integer.class)) {
158                 return Integer.parseInt(value.toString());
159             } else if (destClass.equals(short.class) || destClass.equals(Short.class)) {
160                 return Short.parseShort(value.toString());
161             } else if (destClass.equals(byte.class) || destClass.equals(Byte.class)) {
162                 return  Byte.parseByte(value.toString());
163             } else if (destClass.equals(long.class) || destClass.equals(Long.class)) {
164                 return Long.parseLong(value.toString());
165             } else if (destClass.equals(float.class) || destClass.equals(Float.class)) {
166                 return Float.parseFloat(value.toString());
167             } else if (destClass.equals(boolean.class) || destClass.equals(Boolean.class)) {
168                 return Boolean.parseBoolean(value.toString());
169             } else if (destClass.equals(JSONObject.class)) {
170                 return JSONObject.fromObject(value);
171             } else if (destClass.equals(String.class)) {
172                 String valueString = value.toString();
173                 if(valueString.startsWith("\"") && valueString.endsWith("\"")) {
174                     valueString = valueString.substring(1, valueString.length() - 1);
175                 }
176                 return valueString;
177             }
178         } catch (Exception e) {
179         }
180         return value;
181     }
182     
183     public static String getFunctionAndPublicMethod(Class myClass) {
184         JSONObject json = new JSONObject();
185         Field[] fields = myClass.getFields();
186         for(Field field : fields) {
187             json.element(field.getClass().getSimpleName() + "-" + field.getName(), field.getType().getSimpleName());
188         }
189         
190         Method[] methods = myClass.getMethods();
191         for(Method method : methods) {
192             Class[] paramerters = method.getParameterTypes();
193             StringBuilder info = new StringBuilder(method.getName() + "(");
194             for(int i = 0; i < paramerters.length; i++) {
195                 info.append(paramerters[i].getSimpleName() + ",");
196             }
197             info.append(")");
198             json.element(info.toString(), method.getReturnType().getSimpleName());
199         }
200         return json.toString(1,4);
201     }

3。测试

首先Test的的实现如下

    public static Object getProperty(String cctv, int index) {
        return cctv + index;
    }
    
    public static void setProperty() {
        System.out.println("setProperty");
    }
    
    public static String getProperty() {
        return "getProperty";
    }
    
    public static String getProperty(String myContent) {
        return myContent + "getProperty";
    }

 

Test.getProperty(Test.getProperty("hello reflect"), 6x);

未发现匹配的函数,请检查函数的正确性

  Test.getProperty(Test.getProperty("hello reflect"), 6 );
  hello reflectgetProperty6

  Test.setProperty();
  setProperty

成功调用。

完整的源码请参照

http://download.csdn.net/detail/w273732573/5338266

转载于:https://www.cnblogs.com/tickdream/archive/2013/05/06/3063910.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值