扫描Java标注在运行时 [英] Scanning Java annotations at runtime

查看:221
本文介绍了扫描Java标注在运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是搜索整个classpath中的注释类的最佳方式?

我在做一个图书馆,我想允许用户标注自己的班级,所以当Web应用程序启动我需要扫描某些注释整个类路径。

你知道图书馆或Java设施,这样做呢?

编辑:我想是这样的Java EE 5的Web服务或EJB的新功能。你用注释@WebService或@EJB和系统类中找到这些类加载所以他们远程访问。


解决方案

使用<一个href=\"http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.html\">org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider

API


  

这是扫描从基础包classpath中的组件供应商。然后,它适用排除和包括过滤器生成的类来寻找候选人。


  ClassPathScanningCandidateComponentProvider扫描仪=
新ClassPathScanningCandidateComponentProvider(小于DO_YOU_WANT_TO_USE_DEFALT_FILTER&GT);scanner.addIncludeFilter(新AnnotationTypeFilter(小于TYPE_YOUR_ANNOTATION_HERE&GT;的.class));为(的BeanDefinition BD:scanner.findCandidateComponents(小于TYPE_YOUR_BASE_PACKAGE_HERE&GT))
    的System.out.println(bd.getBeanClassName());

What is the best way of searching the whole classpath for an annotated class?

I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scan the whole classpath for certain annotation.

Do you know a library or a Java facility to do this?

Edit: I'm thinking about something like the new functionality for Java EE 5 Web Services or EJB's. You annotate your class with @WebService or @EJB and the system find these classes while loading so they are accessible remotely.

解决方案

Use org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider

API

A component provider that scans the classpath from a base package. It then applies exclude and include filters to the resulting classes to find candidates.

ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFALT_FILTER>);

scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class));

for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>))
    System.out.println(bd.getBeanClassName());

这篇关于扫描Java标注在运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆