简体   繁体   中英

Java - get fields names of certain types

I have an example class below and I want to return all class fields of certain type, in this example of type 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"}
    }
}

I need a help here. How can I find all class fields of certain type. I will be calling this method in another class ofc.

Use reflection to access the fields declared on the class. Then iterate through the fields and check to see if their type matches Image .

You could also create a more useful method by accepting two parameters a target Class and a searchType Class . The method would then searches for fields with the target of the type searchType .

I would also recommend making this method static, since it really doesn't depend on any of the classes state.

Example

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);
        }
    }
}

A simpler alternative to using reflection would be to use a map as the primary data type for the field you are interested in:

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);
    }
}

Using field names as values can cause headaches.

If you need to identify individual images with strings, you could create a HashMap. Use your current field names as keys and Image objects as values.

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

You can retrieve all key values (in your case,the names) via the method keySet()

Edit: Here's a working example class, derived from yours, but only with the relevant fields:

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());
    }
}

use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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