Search code examples
javacompiler-errorstype-conversionjava-6

How to prevent an Object being cast to a String automatically


I have a class that looks like the following:

public class FileEntry {
    private String name;
    public FileEntry (String name) {
        this.name = name;
    }
}

void foo(String arg){};
foo("string" + new FileEntry("")); // How to get a compile error here

How can I make java give me a compile error instead of automatically converting the Object to a String?


Solution

  • If you have

    void foo(String bar)
    {
    
    }
    

    and you call

    foo(new FileEntry());
    

    there will be a compiler error. See here

    The the toString() will be called only if you do something like

    foo("this is foo" + new FileEntry());