集册 Java实例教程 按类型获取字段名称

按类型获取字段名称

欢马劈雪     最近更新时间:2020-01-02 10:19:05

519
按类型获取字段名称


//package com.nowjava;/*N o  w  J a v a . c o m - 时  代  Java 提 供*/

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));

    }


    public static String getFieldNameByType(Class clazz, final Class type)

            throws Exception {

        Field[] fields = clazz.getDeclaredFields();//n o w  j a v a  . c o m 提 供

        List<String> list = new ArrayList();

        for (Field field : fields) {

            if (type == field.getType()) {

                list.add(field.getName());

            }

        }

        if (list.size() > 1) {

            
展开阅读全文