简体   繁体   中英

Why toString is not called for functions parameter?

I have and Enum for my intent Extras I like to use in my android app. The type defenition is written like this:

public enum Extras { TITLE, ID_USER } // ... and some more Extras

in my code I like to use the Enums like this:

Intent i = new Intent(); 
i.putExtra( Extras.TITLE  , "My Title String");
i.putExtra( Extras.ID_USER, 5);

And

 String title = i.getStringExtra(Extras.TITLE);
 int userId   = i.getIntExtra(Extras.ID_USER, -1);

as I know enums have a toString method, my Enum Extras.TITLE should be automatically be casted to the String "TITLE" .

Its even working if I print it to screen like this

System.out.println("Extra="+Extras.TITLE); 

But for the Intent Methods I get the error message:

The method putExtra(String, CharSequence) in the type Intent is not applicable for the arguments (Extras, CharSequence)

I could avoid this error if manually convert the enum to String like this:

i.putExtra( Extras.TITLE.name()  , "My Title String");
i.putExtra( Extras.TITLE.toString()  , "My Title String");

But I like to know why to String issn`t called automatically when I pass my Enum as parameter to this method ?

Is there a way to to pass my Enums without calling toString() ?

UPDATE: I tried to change my Enum to implement CharSequence interface. After this modification I can pass my Enums to methods which expect CharSequence parameters. But it is still incompatible with String methods.

public static enum Extras implements CharSequence { TITLE, ID_USER; // ... and some more Extras

    @Override  public char charAt( int index )                       { return this.toString().charAt(index);           }
    @Override  public int length()                                   { return this.toString().length();                }
    @Override  public CharSequence subSequence( int start, int end ) { return this.toString().subSequence(start, end); }
}

Nope, Enums in Java are Integer values. You cannot cannot get the String value without calling toString() method. See here and here for further info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM