vendredi 24 juin 2016

Checking loaded class has annotations in web application

I wrote my class annotation:

@Documented
@Target(ElementType.METHOD)
@Retention(RUNTIME)
public @interface CAnnotation {
   String name();
}

Next i wrote my lib:

public class Customized implements Serializable{

@CAnnotation(name="getCustomer")
public String getCustomer(int id){
    return "ABCABC";
} 
}

Now I read in web application Customized.jar like this:

public void inir(){
        System.out.println("---------------");
        System.out.println("---------------");
        for (Method metoda : getUserClass().getMethods()) {
            System.out.println("---------------"
                    + "\n" + metoda.isAnnotationPresent(CAnnotation.class)
                    + "\n" + metoda.getName()
            );
            for (Annotation annotation : metoda.getAnnotations()) {
                System.out.println("---------------"
                        + "\n" + annotation
                );
            }
            if (metoda.getAnnotation(CAnnotation.class) instanceof CAnnotation) {
                System.out.println("---------------");
                System.out.println(":" + metoda + " " + metoda.getAnnotation(CAnnotation.class).name());
                System.out.println("---------------");
            }
        }
    }


    public  Class getUserClass() {
        File file = new File("./Customized.jar");
        try {
            JarFile jarFile = new JarFile(file.getPath());
            Enumeration e = jarFile.entries();
            URL[] urls = {new URL("jar:file:" + file.getPath() + "!/")};
            URLClassLoader cl = URLClassLoader.newInstance(urls);
            while (e.hasMoreElements()) {
                JarEntry je = (JarEntry) e.nextElement();
                if (je.isDirectory() || !je.getName().endsWith(".class")) {
                    continue;
                }
                String className = je.getName().substring(0, je.getName().length() - 6);
                className = className.replace('/', '.');
                Class c = cl.loadClass(className);
                return c;
            }
            return null;
        } catch (IOException | ClassNotFoundException ex) {
            System.out.println("" + ex);
            return null;
        }

    }

And in console I get this:

Info:   ---------------
Info:   ---------------
Info:   ---------------
false
getCustomer
Info:   ---------------
...

I checked it in desktop application and i get "true" So what is a difference between web and desktop app, in the web appliction dont have my annotations? What am I doing wrong? I checked a file on server using the jd-gui(Java Decompiler) and customized.jar have annotations. I didn't add anythjing in web or faces-config.





Aucun commentaire:

Enregistrer un commentaire