简体   繁体   English

为什么不为函数参数调用toString?

[英]Why toString is not called for functions parameter?

I have and Enum for my intent Extras I like to use in my android app. 我有Enum和我想要在我的Android应用程序中使用的其他功能。 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" . 据我所知,枚举有一个toString方法,我的Enum Extras.TITLE应该自动转换为字符串"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: 如果将枚举手动转换为String,我可以避免此错误:

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 ? 但是我想知道为什么当我将Enum作为参数传递给此方法时,为什么会自动调用String issn`t吗?

Is there a way to to pass my Enums without calling toString() ? 有没有办法传递我的枚举而不调用toString()吗?

UPDATE: I tried to change my Enum to implement CharSequence interface. 更新:我试图更改我的枚举以实现CharSequence接口。 After this modification I can pass my Enums to methods which expect CharSequence parameters. 修改之后,我可以将Enums传递给需要CharSequence参数的方法。 But it is still incompatible with String methods. 但是它仍然与String方法不兼容。

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. 不, Java中的EnumInteger值。 You cannot cannot get the String value without calling toString() method. 不调用toString()方法就无法获取String值。 See here and here for further info. 有关更多信息,请参见此处此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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