Java - 如何将对象转换为变量?

时间:2012-09-03 20:15:30

标签: java string object int

我正在编写一个编程语言,我需要将一个对象(比如javascript中的var)转换为它应该的变量类型。例如:

if(object == variabletypes.string)
{
//convert object to string
}
else if(object ==variabletypes.int)
{
//convert to integer
}

感谢您的时间,我们将不胜感激。

4 个答案:

答案 0 :(得分:7)

假设你有java.lang.Object,这是一个开始:

Object o = /* ??? */;
if (o instanceof String)
{
    String s = (String) o;
}
else if (o instanceof Integer)
{
    Integer integer = (Integer) o;
    int i = integer.intValue();
}

这里的“转换”主要是casting,假设对象已经具有正确的运行时类型,并且您不需要实际更改内部表示 - 例如,通过更改String intInteger#parseInt()

其他可能有用的方法(因为问题不完全清楚)可能包括:

答案 1 :(得分:2)

if(yourObject instanceof String){
    String str = (String)yourObject;
}
else if (yourObject instanceof Integer){
    Integer yourInt = (Integer)yourObject;
}
else if{
     System.out.println("My object is a class of: "+ yourObject.getClass().getName());
}

答案 2 :(得分:1)

你可以这样做:

object.toString(); // Returns the string value of the object, if it exists.

http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

答案 3 :(得分:1)

您有几种Java工具:

  1. instanceof运算符
  2. getClass().getName()次调用,它将为对象的实际类名称提供字符串。
  3. 我不知道“转换”是什么意思,但这些是你可以使用的基本工具。

相关问题