You can use the class returned by Field getType method. See the example code bellow:

import java.lang.reflect.Field;

    public class Main {

      public static void main(String[] args) {
        Field[] declaredFields = MyClass.class.getDeclaredFields();
        for (Field declaredField : declaredFields) {
          Class<?> fieldType = declaredField.getType();
          String result=fieldType.getName();
          System.out.println(result);
        }
      }

    }

But be careful with primitive data types (example: boolean). In this case the fieldType.getName() function returns a uninstantiated string (boolean). You can handle it differently. The list of internal data types is here.

Answer from voji on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › tutorial › reflect › member › fieldTypes.html
Obtaining Field Types (The Java™ Tutorials > The Reflection API > Members)
Thus T is replaced by the upper bound of the type variable, in this case, java.lang.Object. Field.getGenericType() will consult the Signature Attribute in the class file if it's present. If the attribute isn't available, it falls back on Field.getType() which was not changed by the introduction of generics. The other methods in reflection with name getGenericFoo for some value of Foo are implemented similarly.
🌐
Dev.java
dev.java › learn › reflection › fields
Reading and Writing Fields - Dev.java
July 19, 2024 - So when you are reading a field from an object using reflection, you need to cast the object you get to its exact type. If the type of your field is a primitive type or a wrapper type, you can cast the result of a call to Field.get(Object) to ...
🌐
TutorialsPoint
tutorialspoint.com › javareflect › javareflect_field_gettype.htm
java.lang.reflect.Field.getType() Method Example
Following is the declaration for java.lang.reflect.Field.getType() method. public Class<?> getType() a Class object identifying the declared type of the field represented by this object.
🌐
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 - To test the method, we simply filter the returned array by field names and check their types. Let’s now see how to get the inherited fields of a Java class.
🌐
Tabnine
tabnine.com › home page › code › java › java.lang.reflect.field
java.lang.reflect.Field.getType java code examples | Tabnine
/** * Return the type declared by the underlying field or method/constructor parameter, * indicating the injection type. */ public Class<?> getDeclaredType() { return (this.field != null ? this.field.getType() : obtainMethodParameter().getParameterType()); } ... @Override protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable { Class<?> referenceClass = field.getType(); referenceBean = buildReferenceBean(reference, referenceClass); ReflectionUtils.makeAccessible(field); field.set(bean, referenceBean.getObject()); }
🌐
Learn IT University
learn-it-university.com › home › checking the type of a field using reflection
Checking the Type of a Field Using Reflection - Learn IT University
June 22, 2024 - Finally, we use the isAssignableFrom() method to determine if the field is an instance of SomeType or any of its subclasses. Accuracy: Ensure that the types you are checking are precise to avoid incorrect conclusions.
Find elsewhere
🌐
Mkyong
mkyong.com › home › java › java – find class fields with specified data type
Java - find class fields with specified data type - Mkyong.com
April 28, 2016 - package com.mkyong.test; import java.lang.reflect.Field; import java.util.List; public class Test { public static void main(String[] args) { Field[] fields = CompanyA.class.getDeclaredFields(); for(Field f : fields){ Class t = f.getType(); System.out.println("field name : " + f.getName() + " , type : " + t); } } }
🌐
Jenkov
jenkov.com › tutorials › java-reflection › fields.html
Java Reflection - Fields
April 21, 2016 - You can determine the field type (String, int etc.) of a field using the Field.getType() method:
🌐
W3Schools Blog
w3schools.blog › home › java reflection get field type
Java reflection get field type
June 26, 2019 - The getType() method is used to get field type in java. ... package com.w3spoint; public class TestClass { private int defaultLength = 10; private int defaultWidth = 5; public String testField = "w3spoint"; public void drawShape(String color) { System.out.println("Rectangle create with following ...
🌐
Coderanch
coderanch.com › t › 570649 › java › check-field-primitive-user-defined
How to check given field whether primitive or user defined (Java in General forum at Coderanch)
March 17, 2012 - Hi I am using reflection to get all the declared fields in a given class. using I have two java files the first one is The user defined class is as follows No my question is when i use Field[] fieldsInClass = sample.getDeclaredFields(); It is returning all the declared fields in sample class. I want to check every field whether it is primitive type or user defined . and if the type of a field is user defined then I want to get all the fileds declared in that class(in the above example it is UTC class).
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › reflect › Field.html
Field (Java Platform SE 8 )
3 weeks ago - If the Type is a parameterized ... reflect the actual type parameters used in the source code. If the type of the underlying field is a type variable or a parameterized type, it is created. Otherwise, it is resolved. ... GenericSignatureFormatError - if the generic field signature does not conform to the format specified in The Java™ Virtual ...
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);
    }
}
🌐
CodingTechRoom
codingtechroom.com › question › how-to-determine-if-a-field-is-an-instance-of-a-specific-type-using-reflection-in-java
How to Determine if a Field is an Instance of a Specific Type Using Reflection in Java? - CodingTechRoom
In Java, reflection allows you to inspect classes, fields, and methods at runtime. To check if a field belongs to a specific type T (or any of its supertypes), you need to examine both the field's type and its supertype hierarchy.
Top answer
1 of 9
70

Have a look at Obtaining Field Types from the Java Tutorial Trail: The Reflection API.

Basically, what you need to do is to get all java.lang.reflect.Field of your class and call Field#getType() on each of them (check edit below). To get all object fields including public, protected, package and private access fields, simply use Class.getDeclaredFields(). Something like this:

for (Field field : Person.class.getDeclaredFields()) {
    System.out.format("Type: %s%n", field.getType());
    System.out.format("GenericType: %s%n", field.getGenericType());
}

EDIT: As pointed out by wowest in a comment, you actually need to call Field#getGenericType(), check if the returned Type is a ParameterizedType and then grab the parameters accordingly. Use ParameterizedType#getRawType() and ParameterizedType#getActualTypeArgument() to get the raw type and an array of the types argument of a ParameterizedType respectively. The following code demonstrates this:

for (Field field : Person.class.getDeclaredFields()) {
    System.out.print("Field: " + field.getName() + " - ");
    Type type = field.getGenericType();
    if (type instanceof ParameterizedType) {
        ParameterizedType pType = (ParameterizedType)type;
        System.out.print("Raw type: " + pType.getRawType() + " - ");
        System.out.println("Type args: " + pType.getActualTypeArguments()[0]);
    } else {
        System.out.println("Type: " + field.getType());
    }
}

And would output:

Field: name - Type: class java.lang.String
Field: children - Raw type: interface java.util.List - Type args: class foo.Person
2 of 9
7

I haven't found any framework who determines a generic field type through the inheritance layers so i've written some method:

This logic determines the type through the field information and the current object class.

Listing 1 - logic:

public static Class<?> determineType(Field field, Object object) {
    Class<?> type = object.getClass();
    return (Class<?>) getType(type, field).type;
}

protected static class TypeInfo {
    Type type;
    Type name;

    public TypeInfo(Type type, Type name) {
        this.type = type;
        this.name = name;
    }

}

private static TypeInfo getType(Class<?> clazz, Field field) {
    TypeInfo type = new TypeInfo(null, null);
    if (field.getGenericType() instanceof TypeVariable<?>) {
        TypeVariable<?> genericTyp = (TypeVariable<?>) field.getGenericType();
        Class<?> superClazz = clazz.getSuperclass();

        if (clazz.getGenericSuperclass() instanceof ParameterizedType) {
            ParameterizedType paramType = (ParameterizedType) clazz.getGenericSuperclass();
            TypeVariable<?>[] superTypeParameters = superClazz.getTypeParameters();
            if (!Object.class.equals(paramType)) {
                if (field.getDeclaringClass().equals(superClazz)) {
                    // this is the root class an starting point for this search
                    type.name = genericTyp;
                    type.type = null;
                } else {
                    type = getType(superClazz, field);
                }
            }
            if (type.type == null || type.type instanceof TypeVariable<?>) {
                // lookup if type is not found or type needs a lookup in current concrete class
                for (int j = 0; j < superClazz.getTypeParameters().length; ++j) {
                    TypeVariable<?> superTypeParam = superTypeParameters[j];
                    if (type.name.equals(superTypeParam)) {
                        type.type = paramType.getActualTypeArguments()[j];
                        Type[] typeParameters = clazz.getTypeParameters();
                        if (typeParameters.length > 0) {
                            for (Type typeParam : typeParameters) {
                                TypeVariable<?> objectOfComparison = superTypeParam;
                                if(type.type instanceof TypeVariable<?>) {
                                    objectOfComparison = (TypeVariable<?>)type.type;
                                }
                                if (objectOfComparison.getName().equals(((TypeVariable<?>) typeParam).getName())) {
                                    type.name = typeParam;
                                    break;
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }
    } else {
        type.type = field.getGenericType();
    }

    return type;
}

Listing 2 - Samples / Tests:

class GenericSuperClass<E, T, A> {
    T t;
    E e;
    A a;
    BigDecimal b;
}

class GenericDefinition extends GenericSuperClass<Integer, Integer, Integer> {

}

@Test
public void testSimpleInheritanceTypeDetermination() {
    GenericDefinition gd = new GenericDefinition();
    Field field = ReflectionUtils.getField(gd, "t");
    Class<?> clazz = ReflectionUtils.determineType(field, gd);
    Assert.assertEquals(clazz, Integer.class);
    field = ReflectionUtils.getField(gd, "b");
    clazz = ReflectionUtils.determineType(field, gd);
    Assert.assertEquals(clazz, BigDecimal.class);
}

class MiddleClass<A, E> extends GenericSuperClass<E, Integer, A> { }

// T = Integer, E = String, A = Double
class SimpleTopClass extends MiddleClass<Double, String> { }

@Test
public void testSimple2StageInheritanceTypeDetermination() {
    SimpleTopClass stc = new SimpleTopClass();
    Field field = ReflectionUtils.getField(stc, "t");
    Class<?> clazz = ReflectionUtils.determineType(field, stc);
    Assert.assertEquals(clazz, Integer.class);
    field = ReflectionUtils.getField(stc, "e");
    clazz = ReflectionUtils.determineType(field, stc);
    Assert.assertEquals(clazz, String.class);
    field = ReflectionUtils.getField(stc, "a");
    clazz = ReflectionUtils.determineType(field, stc);
    Assert.assertEquals(clazz, Double.class);
}

class TopMiddleClass<A> extends MiddleClass<A, Double> { }

// T = Integer, E = Double, A = Float
class ComplexTopClass extends TopMiddleClass<Float> {}

@Test void testComplexInheritanceTypDetermination() {
    ComplexTopClass ctc = new ComplexTopClass();
    Field field = ReflectionUtils.getField(ctc, "t");
    Class<?> clazz = ReflectionUtils.determineType(field, ctc);
    Assert.assertEquals(clazz, Integer.class);
    field = ReflectionUtils.getField(ctc, "e");
    clazz = ReflectionUtils.determineType(field, ctc);
    Assert.assertEquals(clazz, Double.class);
    field = ReflectionUtils.getField(ctc, "a");
    clazz = ReflectionUtils.determineType(field, ctc);
    Assert.assertEquals(clazz, Float.class);
}

class ConfusingClass<A, E> extends MiddleClass<E, A> {}
// T = Integer, E = Double, A = Float ; this class should map between a and e
class TopConfusingClass extends ConfusingClass<Double, Float> {}

@Test
public void testConfusingNamingConvetionWithInheritance() {
    TopConfusingClass tcc = new TopConfusingClass();
    Field field = ReflectionUtils.getField(tcc, "t");
    Class<?> clazz = ReflectionUtils.determineType(field, tcc);
    Assert.assertEquals(clazz, Integer.class);
    field = ReflectionUtils.getField(tcc, "e");
    clazz = ReflectionUtils.determineType(field, tcc);
    Assert.assertEquals(clazz, Double.class);
    field = ReflectionUtils.getField(tcc, "a");
    clazz = ReflectionUtils.determineType(field, tcc);
    Assert.assertEquals(clazz, Float.class);
    field = ReflectionUtils.getField(tcc, "b");
    clazz = ReflectionUtils.determineType(field, tcc);
    Assert.assertEquals(clazz, BigDecimal.class);
}

class Pojo {
    Byte z;
}

@Test
public void testPojoDetermineType() {
    Pojo pojo = new Pojo();
    Field field = ReflectionUtils.getField(pojo, "z");
    Class<?> clazz = ReflectionUtils.determineType(field, pojo);
    Assert.assertEquals(clazz, Byte.class);
}

I'm looking forward to hear your feedback!