java 运行注释_在运行时扫描Java注释

但是,即使有人想用Classloader来尝试它,我还是自己写了一些来打印包中类的注释:

public class ElementScanner {

public void scanElements(){

try {

//Get the package name from configuration file

String packageName = readConfig();

//Load the classLoader which loads this class.

ClassLoader classLoader = getClass().getClassLoader();

//Change the package structure to directory structure

String packagePath = packageName.replace('.', '/');

URL urls = classLoader.getResource(packagePath);

//Get all the class files in the specified URL Path.

File folder = new File(urls.getPath());

File[] classes = folder.listFiles();

int size = classes.length;

List> classList = new ArrayList>();

for(int i=0;i

int index = classes[i].getName().indexOf(".");

String className = classes[i].getName().substring(0, index);

String classNamePath = packageName+"."+className;

Class> repoClass;

repoClass = Class.forName(classNamePath);

Annotation[] annotations = repoClass.getAnnotations();

for(int j =0;j

System.out.println("Annotation in class "+repoClass.getName()+ " is "+annotations[j].annotationType().getName());

}

classList.add(repoClass);

}

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

}

/**

* Unmarshall the configuration file

* @return

*/

public String readConfig(){

try{

URL url = getClass().getClassLoader().getResource("WEB-INF/config.xml");

JAXBContext jContext = JAXBContext.newInstance(RepositoryConfig.class);

Unmarshaller um = jContext.createUnmarshaller();

RepositoryConfig rc = (RepositoryConfig) um.unmarshal(new File(url.getFile()));

return rc.getRepository().getPackageName();

}catch(Exception e){

e.printStackTrace();

}

return null;

}

}

在配置文件中,您将包名放在一个类中,然后将其取消标记。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值