Question

This may come across as a relatively stupid question, but I'm getting tired of having to hard code statements such as:

private void doStuff(){
System.out.println(this.getClass().getName().toString()+ someText);{...};}

every time I want to
So I decided to implement an external method which writes in the output stream whenever I decide I need something written there such as:.

public static void println(Object obj, String s) {
    System.out.println(obj.getClass().getName() + " > " + s);
}

So the question is, Is there a way to automatically set the value of the 's' variable in the method above to always default to "initialized" when writing source code (using TAB for code completion e.g. Netbeans)?

Many thanks in advance.

Was it helpful?

Solution

Use varargs as the second method parameter. This will also allow you to pass multiple debug statements.

public class Logger {

    public static void main(String[] args) {
        String test = "Test";
        println(test);
        println(test, "This is a test");
    }

    public static void println(Object obj, String...vargs) {
        String defaultValue = "initialized";
        if(vargs.length == 0){
            System.out.println(obj.getClass().getName() + " > " + defaultValue);
        }else{
            for(String x: vargs){
                System.out.println(obj.getClass().getName() + " > " + x);
            }
        }
    }
}

OTHER TIPS

Why don't you just overload the method with a default value?

public static void println(Object obj) {
    println(obj, "Initalized");
}
public static void println(Object obj, String s) {
    System.out.println(obj.getClass().getName() + " > " + s);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top