user3668129
user3668129

Reputation: 4810

java how to check which type I'm getting from getType function

I want to do some logic according to the Field type.

I'm getting the field (Field class) type:

Field[] fields = o.getClass().getFields();
for (Field field : fields) {
    // which and how to use:
    //Class<?> t = field.getType();
    // Type type = field.getType();
    if (type == byte) {

    } else if (type == int) {

    }
}

How can I know which type I'm getting ?

Upvotes: 0

Views: 48

Answers (1)

Eran
Eran

Reputation: 393771

You can do it like this :

import java.lang.reflect.Field;
import java.lang.reflect.Type;

class Test 
{
    public String s;
    public int member = 1;
    public byte try1 = 0;
    public int member2 = 4;

    public static void main(String []args)
    {
        Test o = new Test ();
        Field[] fields = o.getClass().getFields();
        for (Field field : fields) {                
            Class<?> type = field.getType();
            if (type.equals(byte.class)) {
                System.out.println("byte"); 
            } else if (type.equals(int.class)) {
                System.out.println("int");
            } else {
                System.out.println("something else");
            }    
        }
    }
}

Output :

something else
int
byte
int

Upvotes: 2

Related Questions