mardi 10 juillet 2018

Java: Easy way of passing a method as a parameter

I'm attempting to create a better logging situation for myself. Currently I'm just custom writing a string and logging that string. What I'd like to do instead is know the exact Class#method combination that I'm logging. Currently I'm writing it out such as:

Logger.push(String s) where s is something like "ClassA#myMethod: Successfully implemented database

What I want to do it make it a little easier on myself, my reducing the text I have to write if possible. I don't want to have to type ClassA#myMethod, instead what I want to do is pass a method and use reflection to get the desired names. Here's the example logger function I've created:

public static void push(String msg, Method cont){
    logger.info(cont.getDeclaringClass().getSimpleName() + "#" + cont.getName() + ": " + msg);
}

My issue is with passing the method. Ideally I'm looking for something like this, but for the actual method. Currently the only way I could think of is something like: Logger.push("Hello World", getClass().getDeclaredMethods("thisMethodName");

I was just wondering if there was an easier to get the currently used function. Thanks!





Aucun commentaire:

Enregistrer un commentaire