如果成员在数组中,则isInstance不起作用

时间:2015-08-12 07:14:47

标签: java isinstance

Class X{
    Integer x=new Integer(5);
    Integer y;
    public static void main (String[] args) throws java.lang.Exception
    {
         X i = new X();
         String[] str={"x", "y"};
         System.out.println(Integer.class.isInstance(str[0]));
    }
}

它返回false,因为str [0]是Class String的一个实例。 有没有办法可以返回true,因为str [0] = x而变量“x”是整数类的实例?

感谢。

3 个答案:

答案 0 :(得分:1)

当您执行String[] str={"x", "y"};时,您并未将变量x保存在数组中,而是保存仅包含字符" x&的字符串#34 ;.这不是因为它是一个阵列或它不起作用的任何东西,如果你想x作为Integer,你必须做{{1} }或this.x。在String数组中,它只是两个字符串,而不是您在i.x中创建的具有相同名称的值。

编辑:如果您要在i中保存xy,请执行以下操作:

i

如果要将这些值作为String:

Integer[] ints= {i.x, y.x};
System.out.println(Integer.class.isInstance(ints[0]);

答案 1 :(得分:0)

您的课程等同于以下代码: -

public  class X {
        public static void main (String[] args) throws java.lang.Exception
        {
             String[] str={"x", "y"};
             System.out.println(Integer.class.isInstance(Integer.parseInt(str[0])));
        }
    }

您正在尝试在Integer和随机字符串(在本例中为x和y)之间进行比较,该字符串无法解析为整数。在这种情况下,您无法将字符串解析为整数。请参阅下面的示例,它可能会让您明白: -

public  class X {
        public static void main (String[] args) throws java.lang.Exception
        {
             String[] str={"5", "7"};
              System.out.println(Integer.class.isInstance(str[0]));
        }
    }

仍然返回false。

将其更改为

 System.out.println(Integer.class.isInstance(Integer.parseInt(str[0])));

将返回true。

答案 2 :(得分:0)

感谢您的帮助。我是这样做的。

class A
{
    public Integer x=new Integer(5);
    public Integer y=new Integer(7);
    public static void main (String[] args) throws java.lang.Exception
    {
        A i=new A();
        String[] s = {"allowedFileTypeMap","x","y"};
        Field field = i.getClass().getField(s[1]);
        if(field!=null){
            Object fieldType = field.getType();
            System.out.println(fieldType);
            if(field.getType().isAssignableFrom(Integer.class)){
                System.out.println("Working");
            }
        }       
    }
}