通过反射获取自定义类
package helloworldser;import java.util.Map;import javax.servlet.http.HttpServletRequest;
import org.osoa.sca.annotations.Service;
import com.sunsheen.jfids.system.base.composite.data.page.java.IPageDataObjectSource;
/** * 一个定义了sca服务的类 */
@Service(interfaces={IPageDataObjectSource.class,HelloWorldService.class})
//@Service(IPageDataObjectSource.class)
public class HelloWorldImpl implements IPageDataObjectSource, HelloWorldService
{...}
反射获取:sca反射获取service定义的类有点麻烦的就是,它的注解有value,跟interface两种定义,如果只有一个服务,一个接口,那么我们就只需要获取它的value,如果有两个service服务定义,则值就存在interface的数组之中。所以这里还有进行一个判断,是多个还是一个。
package helloworldser;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import org.osoa.sca.annotations.Service;
public class Test1 {
/**
* @org.osoa.sca.annotations.Service(value=class java.lang.Void,
* interfaces=[interface
* com.sunsheen
* .jfids.system.base
* .composite.data.page.java.
* IPageDataObjectSource,
* interface helloworldser.
* HelloWorldService])
* @org.osoa.sca.annotations.Service(value= interface
* com.sunsheen.jfids.system
* .base.composite.data.page.java.
* IPageDataObjectSource,
* interfaces=[])
*
*
* @param args
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException {
Service annotations1 = HelloWorldImpl.class
.getAnnotation(Service.class);
Class<?>[] a = annotations1.interfaces();
//如果定义了多个服务,则为一个数组
if (a.length > 0) {
System.err.println("bbb===" + a[1].getName());
} else {
//如果只有一个服务,则直接获取value
Class<?> b = annotations1.value();
System.err.println("bb===" + b.getName());
}
}
}
利用javassist获取:
ClassPool pool = ClassPool.getDefault();
try {
CtClass ctClass = pool.get("helloworldser.HelloWorldImpl");
System.err.println("bbb===" + ctClass.getName());
Service annotations1 =(Service) ctClass.getAnnotation(Service.class);
Class<?>[] a = annotations1.interfaces();
if (a.length > 0) {
System.err.println("bbb===" + a[1].getName());
} else {
Class<?> b = annotations1.value();
System.err.println("bb===" + b.getName());
}
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
本文介绍如何使用Java反射及Javassist工具获取Sca服务定义的类信息,包括单个服务与多个服务的情况,并提供了具体的实现代码。
451

被折叠的 条评论
为什么被折叠?



