简体   繁体   English

将值设置为原始类型字段

[英]Set value to primitive type fields

This is the first time that I'm working with reflection and I have the following trouble. 这是我第一次进行反射,遇到以下麻烦。

I have this class 我有这堂课

public class MyObject {

    private String description;

    private int number;

    private double value;


    //Constructor getter and setter
}

Now I'm trying to set the values of the MyObject's fields. 现在,我试图设置MyObject字段的值。

    Class c = Class.forName("myPackage.MyObject");
    Field [] fields = c.getDeclaredFields();


    for(Field field: fields){

         if(f.getType().equals(Double.class)){
        //Do somethings
        }
        else if(f.getType().equals(Integer.class)){
        //Do somethings
        }
        else{
        //Do somethings
        }


    }
}

but I'm never able to filter int and double type. 但我永远无法过滤int和double类型。

How can I fix it? 我该如何解决?

That is because Double is not double . 那是因为Double不是double Try this instead 试试这个

 if(f.getType() == double.class){
    //Do somethings

 } else if(f.getType() == int.class){
    //Do somethings

 } else {
    //Do somethings
 }

A simple way to prove this to yourself is 向自己证明这一点的简单方法是

 System.out.println(f.getType());

Double.class refers to the wrapper class, java.lang.Double . Double.class引用包装器类java.lang.Double The primitive double is referenced by Double.TYPE . Double.TYPE引用原始double

Similarly, you also have Integer.TYPE , Long.TYPE , etc. 同样,您还具有Integer.TYPELong.TYPE等。

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

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