lundi 21 septembre 2015

Java reflection with logback

I want to log methods and parameters passes to the methods. Only those parameters are to be logged that are annotated. I am thinking to use java reflection for the same. My code is:

final StackTraceElement[] stes = Thread.currentThread().getStackTrace();
        final StackTraceElement ste = stes[stes.length - 2];
        final String methodName = ste.getMethodName();
        final String className = ste.getClassName();//.substring(0,ste.getClassName().indexOf("$")); 
        Class<?> currentClass = null;
        try {
            currentClass = Class.forName(className);
        } catch (ClassNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        Annotation[][] paramAnnotations = null;
        try {
            for (Method m: currentClass.getMethods()) {
                if(m.getName()==methodName){
                     paramAnnotations = m.getParameterAnnotations();
                }

                }
            //paramAnnotations = currentClass.getMethod(methodName,Produces.class).getParameterAnnotations();
        }  catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   

But with this, i cannot relate which parameter had annotation as the method getparameterAnnotations just give the names of the annotation. I somehow need to link the parameter name and annotation with the particular parameter. Please help. Thanks. @Dārayavahuš tdi @harsh @Damian Leszczyński - Vash





Aucun commentaire:

Enregistrer un commentaire