研究下基于java反射调用dubbo业务接口

调用代码

Lang: java
 1//业务service名字
 2String serviceCls = "com.xu81.InnerService";
 3//业务service方法名
 4String serviceMethod = "getById";
 5//实体字段名
 6String fieldName = "id";
 7Class dataCls = Class.forName(serviceCls);
 8Field idField = null;
 9try {    
10    //获得对象属性    
11    idField = dataCls.getDeclaredField(fieldName);
12} catch (NoSuchFieldException ex) {    
13    log.error("无法获取id属性, 获取父类属性");    
14    //获得父类对象属性    
15    Class supercls = dataCls.getSuperclass();    
16    idField = supercls.getDeclaredField(fieldName);
17}
18try {    
19    if (idField != null) {        
20        idField.setAccessible(true);  
21        //获取data对象属性值
22        Object dataId = idField.get(data);        
23        Class byidcls = Class.forName(serviceCls);        
24        Object byidclsEntity = context.getBean(getBeanName(serviceCls));        
25        Method byidmethod = byidcls.getMethod(serviceMethod, new Class[]{Long.class});     
26        //方法调用
27        Object result = byidmethod.invoke(byidclsEntity, dataId); 
28    }
29} catch (Exception ex) {    
30    log.error("调用duboo业务报错报错");
31}

getBeanName内容

getBeanName方法内容, 根据业务名自动获得springbean实体名, 要求注入实体必须是interface首字母小写

Lang: java
1private String getBeanName(String str) {2    String name = str.substring(str.lastIndexOf(".") + 1, str.length());3    name = name.substring(0, 1).toLowerCase() + name.substring(1, name.length());4    return name;// InnerService -> innerService
5}