Try this

import java.lang.reflect.Field;
public class ToStringMaker {
  public ToStringMaker( Object o) {

  Class<? extends Object> c = o.getClass();
  Field[] fields = c.getDeclaredFields();
  for (Field field : fields) {
      String name = field.getName();  
    field.setAccessible(true);          
      try {
        System.out.format("%n%s: %s", name, field.get(o));
      } catch (IllegalArgumentException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
  }
 }}
Answer from mottaman85 on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › core java › retrieve fields from a java class using reflection
Retrieve Fields from a Java Class Using Reflection | Baeldung
January 4, 2026 - In this case, we can use the Java Reflection API method Class::getSuperclass(). The .getSuperClass() method returns the superclass of our class without referring explicitly to the name of the superclass. Now, we can get all the fields from the superclass and merge them into a single array:
🌐
Baeldung
baeldung.com › home › java › core java › get all record fields and its values via reflection
Get All Record Fields and Its Values via Reflection | Baeldung
January 16, 2024 - However, the problem can be solved without using the new RecordComponent class. Java reflection API provides the Class.getDeclaredFields() method to get all declared fields in the class.
🌐
Jenkov
jenkov.com › tutorials › java-reflection › fields.html
Java Reflection - Fields
April 21, 2016 - Once you have obtained a Field instance, you can get its field name using the Field.getName() method, like this: Field field = ... //obtain field object String fieldName = field.getName(); You can determine the field type (String, int etc.) ...
🌐
Oracle
docs.oracle.com › javase › tutorial › reflect › member › fieldValues.html
Getting and Setting Field Values (The Java™ Tutorials > The Reflection API > Members)
Methods for getting and setting other primitive types are described in Field. import java.lang.reflect.Field; import java.util.Arrays; import static java.lang.System.out; enum Tweedle { DEE, DUM } public class Book { public long chapters = 0; public String[] characters = { "Alice", "White Rabbit" }; public Tweedle twin = Tweedle.DEE; public static void main(String...
🌐
Tabnine
tabnine.com › home page › code › java › org.reflections.reflectionutils
org.reflections.ReflectionUtils.getFields java code examples | Tabnine
* @return the list of all the telemetry field names in this class. */ public List<String> createTelemetryFieldList() { TelemetryCategory telemetryCategory = this.getClass().getAnnotation(TelemetryCategory.class); List<String> fieldsList = new ArrayList<>(); if (!telemetryCategory.isOneMapMetric()) { Set<Field> fields = ReflectionUtils.getFields(this.getClass(), ReflectionUtils.withAnnotation(TelemetryField.class)); for (Field field : fields) { String fieldName = telemetryCategory.id() + ":" + field.getName(); fieldsList.add(fieldName); } } return fieldsList; }
🌐
Netjstech
netjstech.com › 2017 › 07 › reflection-in-java-field.html
Reflection in Java - Getting Field Information | Tech Tutorials
December 23, 2021 - Name field name All Fields - [public ... to know the types of fields in any class using Java reflection API you can do it using the methods getType() and getGenericType()....
Top answer
1 of 4
16

Something like this...

import java.lang.reflect.Field;

public class Test {
    public static void main(String... args) {
        try {
            Foobar foobar = new Foobar("Peter");
            System.out.println("Name: " + foobar.getName());
            Class<?> clazz = Class.forName("com.csa.mdm.Foobar");
            System.out.println("Class: " + clazz);
            Field field = clazz.getDeclaredField("name");
            field.setAccessible(true);
            String value = (String) field.get(foobar);
            System.out.println("Value: " + value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Foobar {
    private final String name;

    public Foobar(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}

Or, you can use the newInstance method of class to get an instance of your object at runtime. You'll still need to set that instance variable first though, otherwise it won't have any value.

E.g.

Class<?> clazz = Class.forName("com.something.Foobar");
Object object = clazz.newInstance();

Or, where it has two parameters in its constructor, String and int for example...

Class<?> clazz = Class.forName("com.something.Foobar");
Constructor<?> constructor = clazz.getConstructor(String.class, int.class);
Object obj = constructor.newInstance("Meaning Of Life", 42);

Or you can interrogate it for its constructors at runtime using clazz.getConstructors()

NB I deliberately omitted the casting of the object created here to the kind expected, as that would defeat the point of the reflection, as you'd already be aware of the class if you do that, which would negate the need for reflection in the first place.

2 of 4
2

You can create instance from class object and that can be used in field get value.

 Class modelClass = Class.forName("com.gati.stackoverflow.EX");
    final Field field = modelClass.getDeclaredField("value");
    field.setAccessible(true);
    Object modelInstance=modelClass.newInstance();
    field.get(modelInstance);
Find elsewhere
🌐
Narendra Kadali
narendrakadali.wordpress.com › 2011 › 08 › 27 › 41
Getting All Field Names and their corresponding values using Java Reflection | Narendra Kadali
April 21, 2012 - This entry was posted on August 27, 2011, 5:56 AM and is filed under Java, Programming, Uncategorized. You can follow any responses to this entry through RSS 2.0. You can leave a response, or trackback from your own site. ... Class clazz = allPersons.getClass() ; List l = new Mirror().on(clazz).reflectAll().fields(); for (int i = 0; i < l.size()-1; i++) { Object value = new Mirror().on(target).get().field(l.get(i).getName()); atualizacao.append(l.get(i).getName() +"="+ value+";"); }
🌐
GeeksforGeeks
geeksforgeeks.org › java › field-getname-method-in-java-with-examples
Field getName() method in Java with Examples - GeeksforGeeks
August 26, 2019 - // Java program to demonstrate getName() method import java.lang.reflect.Field; import java.time.Month; public class GFG { public static void main(String[] args) throws Exception { // Get all field objects of Month class Field[] fields = ...
🌐
W3processing
w3processing.com › index.php
Free online tutorials in programming
Java Reflection · To find the public fields of a class, you must invoke the getFields() method on the Class object. The getFields() method will return an array of public Field objects which also includes those inherited from the super-classes as well. Class rectangleClassObject = Rectangle.class; ...
Top answer
1 of 3
147

You can use Class#getDeclaredFields() to get all declared fields of the class. You can use Field#get() to get the value.

In short:

Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
    field.setAccessible(true); // You might want to set modifier to public first.
    Object value = field.get(someObject); 
    if (value != null) {
        System.out.println(field.getName() + "=" + value);
    }
}

To learn more about reflection, check the Oracle tutorial on the subject.

That said, if that VO is a fullworthy Javabean, then the fields do not necessarily represent real properties of a VO. You would rather like to determine the public methods starting with get or is and then invoke it to grab the real property values.

for (Method method : someObject.getClass().getDeclaredMethods()) {
    if (Modifier.isPublic(method.getModifiers())
        && method.getParameterTypes().length == 0
        && method.getReturnType() != void.class
        && (method.getName().startsWith("get") || method.getName().startsWith("is"))
    ) {
        Object value = method.invoke(someObject);
        if (value != null) {
            System.out.println(method.getName() + "=" + value);
        }
    }
}

That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans. There's even a built-in one provided by Java SE in the java.beans package.

BeanInfo beanInfo = Introspector.getBeanInfo(someObject.getClass());
for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
    Method getter = property.getReadMethod(); 
    if (getter != null) {
        Object value = getter.invoke(someObject);
        if (value != null) {
            System.out.println(property.getName() + "=" + value);
        }
    }
}
2 of 3
12

Here's a quick and dirty method that does what you want in a generic way. You'll need to add exception handling and you'll probably want to cache the BeanInfo types in a weakhashmap.

public Map<String, Object> getNonNullProperties(final Object thingy) {
    final Map<String, Object> nonNullProperties = new TreeMap<String, Object>();
    try {
        final BeanInfo beanInfo = Introspector.getBeanInfo(thingy
                .getClass());
        for (final PropertyDescriptor descriptor : beanInfo
                .getPropertyDescriptors()) {
            try {
                final Object propertyValue = descriptor.getReadMethod()
                        .invoke(thingy);
                if (propertyValue != null) {
                    nonNullProperties.put(descriptor.getName(),
                            propertyValue);
                }
            } catch (final IllegalArgumentException e) {
                // handle this please
            } catch (final IllegalAccessException e) {
                // and this also
            } catch (final InvocationTargetException e) {
                // and this, too
            }
        }
    } catch (final IntrospectionException e) {
        // do something sensible here
    }
    return nonNullProperties;
}

See these references:

  • BeanInfo (JavaDoc)
  • Introspector.getBeanInfo(class) (JavaDoc)
  • Introspection (Sun Java Tutorial)
Top answer
1 of 4
6

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);
        }
    }
}
2 of 4
2

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);
    }
}
🌐
W3Schools Blog
w3schools.blog › home › java reflection get all public fields
Java reflection get all public fields
June 26, 2019 - The getFields() method is used to get the array of public fields of the Class. ... package com.w3spoint; public class Rectangle { private int defaultLength = 10; private int defaultWidth = 5; public String testField; public void drawShape(String color) { System.out.println("Rectangle create ...
🌐
Coderanch
coderanch.com › t › 373499 › java › reflection-fields-public
Using reflection to get ALL fields, not just public ones (Java in General forum at Coderanch)
Also it's possible to get at the info in the private field using reflection, or if the class is Serializable you can write it to a file and see that the file contains data from private superclass fields. However these fields are still not considered accessible in the sense that you can access them by simply wrting the name of the field like you can for most other fields.