I am trying to figure out what I am doing wrong.
I have implemented two custom annotation stored in main jar file and in other jar some test classes marked with this annotations.
The idea is load classes from other jar files which match with certain criteria ( my custom annotations in this case)
I can load the classes and get the Annotations with getAnnotations().
But using the method isAnnotationPresent not. Always return false;
I would like to know how to fix this.
Thanks
The Annotations code
package reflectordemo.interfaces;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ClassDescription
{
String text();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SortAlgorithm {}
The demo jar lib code. Note: Reflectordemo is the main jar file and is referenced at compile time
package ppk.classes;
import reflectordemo.interfaces.*;
@SortAlgorithm
@ClassDescription(text = "Bubble sort algorithm")
public class BubbleSort
{
}
@SortAlgorithm
@ClassDescription(text = "Quick sort algorithm")
public class QuickSort
{
}
public class NaiveSort { }
The Loader class
package reflectordemo;
import java.io.FileInputStream;
import java.util.jar.JarInputStream;
import java.util.jar.JarEntry;
import java.lang.annotation.Annotation;
import java.lang.Class;
import java.lang.ClassLoader;
import java.net.URLClassLoader;
import java.net.URL;
import java.io.File;
import reflectordemo.interfaces.*;
public final class Reflector
{
public static void Listclasses(String file)
{
try
{
JarEntry current;
String currentname;
File curfile = new File(file);
try
(
FileInputStream stream = new FileInputStream(file);
JarInputStream j = new JarInputStream(stream);
URLClassLoader cl = URLClassLoader.newInstance(new URL[] {curfile.toURL()},ClassLoader.getSystemClassLoader())
)
{
while ( (current = j.getNextJarEntry()) != null )
{
if ( current.getName().endsWith(".class") )
{
currentname = current.getName().replace(".class","");
String classname = currentname.replace('/', '.');
System.out.println(currentname);
Class w = cl.loadClass(classname);
//Annotation[] ans = w.getAnnotations();
if ( w.isAnnotationPresent(SortAlgorithm.class) == true )
{
System.out.println(classname + " has SortAlgorithm Annotation");
}
else
{
System.out.println(classname + " Not match with criteria");
}
}
}
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Aucun commentaire:
Enregistrer un commentaire