Java 如何获取被注解的类元素
比如定义了一个@controller的注解然后有如下代码
@controller
public class Test1{
}
@controller
public class Test2{
}
@controller
public class Test3{
}
现在怎么在main方法获取到所有被@controller注解的类 --------------------编程问答-------------------- 先取package信息,然后把所有class找到,接着挨个class看是否有你指定的annotation.
例子:
private List<Class> getClassesForPackage(String pckgname)
throws ClassNotFoundException {
//There may be more than one if a package is split over multiple jars/paths
List<Class> classes = new ArrayList<Class>();
String className = "";
try {
ClassLoader cld = Thread.currentThread().getContextClassLoader();
if (cld == null) {
throw new ClassNotFoundException("Can't get class loader.");
}
String pckgnmePathStr = pckgname.replace('.', '/');
// Ask for all resources for the path
Enumeration<URL> resources = cld.getResources(pckgnmePathStr);
while (resources.hasMoreElements()) {
URL res = resources.nextElement();
if (res.getProtocol().equalsIgnoreCase("jar")){
JarURLConnection conn = (JarURLConnection) res.openConnection();
JarFile jar = conn.getJarFile();
for (JarEntry e:Collections.list(jar.entries())){
if (e.getName().startsWith(pckgnmePathStr)
&& e.getName().endsWith(".class") && !e.getName().contains("$")){
String name = e.getName().substring(pckgnmePathStr.length() + 1);
// Do not discover classes in the sub-package
if(name.indexOf('/') > -1) continue;
className =
e.getName().replace("/",".").substring(0,e.getName().length() - 6);
try {
classes.add(Class.forName(className));
}catch(NoClassDefFoundError ncdfe) {}
}
}
}
}
} catch (NullPointerException x) {
throw new ClassNotFoundException(pckgname + " does not appear to be " +
"a valid package (Null pointer exception)");
} catch (UnsupportedEncodingException encex) {
throw new ClassNotFoundException(pckgname + " does not appear to be " +
"a valid package (Unsupported encoding)");
} catch (IOException ioex) {
throw new ClassNotFoundException("IOException was thrown when trying " +
"to get all resources for " + pckgname, ioex);
} catch (Throwable te){
throw new ClassNotFoundException("IOException was thrown when trying " +
"to get all resources for " + pckgname + className, te);
}
return classes;
}
private static Map<String, NamedQueryDefinition> extractNamedQueries(List<Class> classes) {
HashMap<String, NamedQueryDefinition> queryDefs = new HashMap<String, NamedQueryDefinition>();
for(Class clz : classes) {
controller queries = (JpaQueries)clz.getAnnotation(controller.class);
if(queries != null) {
JpaQuery[] queryArray = queries.value();
for(int i = 0; i < queryArray.length; i++) {
queryDefs.put(queryArray[i].name(), new NamedQueryDefinition(
queryArray[i].query(), false, null, null, null, null, null));
}
}
}
return queryDefs;
}
in your main:
List<Class> classes = getClassesForPackage("com.your.package.name");
config.getNamedQueries().putAll(extractNamedQueries(classes));
--------------------编程问答-------------------- 不否认这段代码满足一部分情况
但在某些特殊场合不行
比如maven项目在cmd 用tomcat:run启动的时候
应该跟注释有关的类什么的 比如注释处理器什么的 --------------------编程问答-------------------- 关注一下,楼主这样做到底出于什么考虑啊
补充:Java , Java SE