Java - 获取某些类型的字段名称

时间:2014-12-11 22:15:57

标签: java reflection

我在下面有一个示例类,我希望返回某些类型的所有类字段,在此类型为Image的示例中。

public class Contact {
    private String surname, lastname, address;
    private int age, floor;
    private Image contactPhoto, companyPhoto;
    private boolean isEmployed;

    public String[] getAllImages() {
        String images[] = // missing code
        return images;
        // in this case, I want to return {"contactPhoto","companyPhoto"}
    }
}

我需要一个帮助。如何查找特定类型的所有类字段。我将在另一个类c中调用此方法。

4 个答案:

答案 0 :(得分:5)

使用反射来访问类中声明的字段。然后遍历字段并检查其类型是否与Image匹配。

您还可以通过接受目标Class和searchType Class这两个参数来创建更有用的方法。然后,该方法将搜索target类型为searchType的字段。

我还建议将此方法设为静态,因为它实际上并不依赖于任何类状态。

示例

public class Contact {
    private String surname, lastname, address;
    private int age, floor;
    private Image contactPhoto, companyPhoto;
    private boolean isEmployed;

    public static String[] getFieldsOfType(Class<?> target, Class<?> searchType) {

        Field[] fields  = target.getDeclaredFields();

        List<String> results = new LinkedList<String>();
        for(Field f:fields){
            if(f.getType().equals(searchType)){
                results.add(f.getName());
            }
        }
        return results.toArray(new String[results.size()]);
    }

    public static String[] getAllImages(){
        return getFieldsOfType(Contact.class, Image.class); 
    }

    public static void main(String[] args) {
        String[] fieldNames = getAllImages();

        for(String name:fieldNames){
            System.out.println(name);
        }
    }
}

答案 1 :(得分:2)

使用反射的一个更简单的替代方法是使用地图作为您感兴趣的字段的主要数据类型:

public class Contact {

    private static final String CONTACT_PHOTO = "contactPhoto";
    private static final String COMPANY_PHOTO = "companyPhoto";

    private String surname, lastname, address;
    private int age, floor;
    private HashMap<String, Image> images;
    private boolean isEmployed;

    public Contact() {
        images = new HashMap<String, Image>();
        images.put(CONTACT_PHOTO, null);
        images.put(COMPANY_PHOTO, null);
    }

    public String[] getAllImages() {
        Set<String> imageNames = images.keySet();
        return imageNames.toArray(new String[imageNames.size()]);
    }

    public void setContactPhoto(Image img) {
        images.put(CONTACT_PHOTO, img);
    }

    public Image getContactPhoto() {
        return images.get(CONTACT_PHOTO);
    }

    public void setCompanyPhoto(Image img) {
        images.put(COMPANY_PHOTO, img);
    }

    public Image getCompanyPhoto() {
        return images.get(COMPANY_PHOTO);
    }
}

答案 2 :(得分:1)

将字段名称用作值会导致令人头疼。

如果您需要使用字符串识别单个图像,则可以创建HashMap。 使用当前字段名称作为键,将Image对象用作值。

https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

您可以通过方法keySet()

检索所有键值(在您的情况下,名称)

编辑:这是一个工作示例类,派生自您的,但仅限于相关字段:

import java.awt.Image;
import java.util.HashMap;
import java.util.Set;

public class Contact
{
    private HashMap<String, Image> images;

    public Contact ()
    {
        images = new HashMap<String, Image>();
        images.put( "contactPhoto", null);
        images.put( "companyPhoto", null);
    }

    public Set<String> getAllImages()
    {
        return images.keySet();
    }

    public static void main(String[] args)
    {
        System.out.println(new Contact().getAllImages());
    }
}

答案 3 :(得分:0)

使用:

Field[] fields=this.getClass().getFields();
...
 for (...){
  if ( fields[i].getType() == ?? ){
  ...
  }
 }