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()....
🌐
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+";"); }
Find elsewhere
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);
🌐
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; ...
🌐
Spring
docs.spring.io › spring-framework › docs › 4.2.7.RELEASE_to_4.2.8.RELEASE › Spring Framework 4.2.8.RELEASE › org › springframework › util › ReflectionUtils.html
ReflectionUtils
Invoke the given callback on all fields in the target class, going up the class hierarchy to get all declared fields. ... public static void doWithFields(java.lang.Class<?> clazz, ReflectionUtils.FieldCallback fc, ReflectionUtils.FieldFilter ff)
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.
🌐
Kodejava
kodejava.org › how-do-i-get-fields-of-a-class-object
How do I get fields of a class object? - Learn Java by Examples
May 21, 2023 - The example below using reflection to obtain the fields of a class object. We'll get the field names and their corresponding type. There are three ways shown below which can be used to get an object fields: Class.getDeclaredFields() Class.getFields() Class.getField(String) package org.kodejava.lang.reflect; import java.util.Date; import java.lang.reflect.Field; public class GetFields { public Long id; protected String…