2011-02-23 86 views
1

在java中,我可以将我自己的类设计为可转换(或castable?)为原始类型?举例来说,如果我有:制作自定义对象可转换

Class IntString{ 
    private int intVal; 
    private String strVal; 

    public IntString(int intVal, String strVal){ 
    this.intVal = intVal; 
    this.strVal = strVal; 
    } 
} 

static void main(String[] args){ 
    IntString intStr = new IntString(1,"yes"); 
} 

是否有可能有类似:

int intTstVal = intStr; 

甚至

int intTstVal = (int)intStr; 

而且我也可以用类似的方式使字符串工作?

感谢

回答

2

不会隐但是你可以实现相同/相似的方法来与包装使用。

int intTstVal = intStr.intValue(); 

String text = intStr.stringValue(); 
+2

嗨,彼得,谢谢你的回复。但这是非常明显的。这不是'可兑换'或'铸造'。 – user630286 2011-02-23 15:13:52

-1

不,你显然正在试图模仿PHP,Javascript或Python等松散类型的语言,但Java不是这样的语言。对于基本类型,你试图做的事是不可能的。你可能可以用泛型方法和类型转换,但我认为这不是最好的解决方案。

顺便说一句,你到底在做什么?

+0

为迟到的答复家人道歉。克苏鲁可能是对的。我想要做的是创建一个自定义枚举。我知道enum在那里。但它不适用于MIDP2.0。我仍然可以在一定程度上进步;但不能在switch case语句中使用它们。一个例子是: – user630286 2011-03-01 14:09:31

+0

'public final class MyEnum {0} {0} {0}私人final int代码; private final String desc; private MyEnum(final int code,final String desc)this.code = code; this.desc = desc; } public int getCode(){ return code; } public String getDesc(){ return desc; } public static MyEnum VAL1 = new MyEnum(0,“Val1”); public static MyEnum VAL2 = new MyEnum(2,“Val2”); } ' – user630286 2011-03-01 14:21:13

相关问题