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

调用代码

//业务service名字
String serviceCls = "com.xu81.InnerService";
//业务service方法名
String serviceMethod = "getById";
//实体字段名
String fieldName = "id";
Class dataCls = Class.forName(serviceCls);
Field idField = null;
try {    
    //获得对象属性    
    idField = dataCls.getDeclaredField(fieldName);
} catch (NoSuchFieldException ex) {    
    log.error("无法获取id属性, 获取父类属性");    
    //获得父类对象属性    
    Class supercls = dataCls.getSuperclass();    
    idField = supercls.getDeclaredField(fieldName);
}
try {    
    if (idField != null) {        
        idField.setAccessible(true);  
        //获取data对象属性值
        Object dataId = idField.get(data);        
        Class byidcls = Class.forName(serviceCls);        
        Object byidclsEntity = context.getBean(getBeanName(serviceCls));        
        Method byidmethod = byidcls.getMethod(serviceMethod, new Class[]{Long.class});     
        //方法调用
        Object result = byidmethod.invoke(byidclsEntity, dataId); 
    }
} catch (Exception ex) {    
    log.error("调用duboo业务报错报错");
}

getBeanName内容

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

private String getBeanName(String str) {    String name = str.substring(str.lastIndexOf(".") + 1, str.length());    name = name.substring(0, 1).toLowerCase() + name.substring(1, name.length());    return name;// InnerService -> innerService
}