Question

I'm trying to create a method which can accept objects of a variety of types, perform toString on whatever object is passed in, and then print it. Sometimes it will be an int, sometimes a long, sometimes a string, sometimes a custom object, etc. The only assertion should be that it has a toString() method. Basically, I want to simulate python's duck-typing, rather than having to call toString() outside of this API every time I use the method.

This was the existing functionality:

/**
 * Log a message at TEST level
 * @param message: The message to log
 */
public void test(String message) {
    log(Level.TEST, message);
}

Here's what I have so far in attempting to enhance it:

/**
 * Log a message at TEST level
 * @param message: An object of any class that implements toString.
 */
public void test(Class<?> message) {
    String messageString = message.toString();
    log(Level.TEST, messageString);
}

This seems syntactically correct, but it doesn't give what I want:

Cannot resolve method 'test(int)'

Is there a sound way to achieve this functionality in Java?

Was it helpful?

Solution

public void test(Object message) {
    log(Level.TEST, message.toString());
}

Autoboxing will take care of primitives. Fair warning though: the default output of many (most?) toString() methods isn't very readable, since they defer to the Object.toString() method.

OTHER TIPS

Any class will have a toString() method, because java.lang.Object has it. Therefore, your assertion is sort of... pointless.

As @Kevin mentioned, use Object message instead of Class clazz and that will do it. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top