get Field Name By Type - Java Reflection

Java examples for Reflection:Field Get

Description

get Field Name By Type

Demo Code


//package com.java2s;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        Class type = String.class;
        System.out.println(getFieldNameByType(clazz, type));
    }/*from w  w  w .ja  v  a2s.  c  om*/

    public static String getFieldNameByType(Class clazz, final Class type)
            throws Exception {
        Field[] fields = clazz.getDeclaredFields();
        List<String> list = new ArrayList();
        for (Field field : fields) {
            if (type == field.getType()) {
                list.add(field.getName());
            }
        }
        if (list.size() > 1) {
            throw new Exception(clazz.getSimpleName() + "?"
                    + type.getSimpleName() );
        }
        return list.iterator().next();
    }
}

Related Tutorials