/* * Copyright (c) 2019. 黄钰朝 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hyc.wechat.util; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedList; /** * @author 黄钰朝 * @program XHotel * @description 用于反射的工具 * @date 2019-04-20 02:28 */ public class ReflectUtils { /** * 获取指定对象的所有方法(包括其父类的方法) * * @param obj 需要获取方法的实例对象 * @return 返回一个包含所有方法的LinkedList */ public static LinkedList getMethods(Object obj) { return getMethods(obj.getClass()); } /** * 获取指定类的所有方法(包括其父类的方法) * * @param clazz 需要获取方法的类 * @return 返回一个包含所有方法的LinkedList */ public static LinkedList getMethods(Class clazz) { LinkedList methods = new LinkedList<>(); for (Class cla = clazz; cla != Object.class; cla = cla.getSuperclass()) { methods.addAll(Arrays.asList(cla.getDeclaredMethods())); } return methods; } /** * 获取指定对象的所有字段(包括其父类的字段) * * @param obj 需要获取字段的实例对象 * @return 返回一个包含所有字段的LinkedList */ public static LinkedList getFields(Object obj) { return getFields(obj.getClass()); } /** * 获取指定类的所有字段(包括其父类的字段) * * @param clazz 需要获取字段的类 * @return 返回一个包含所有字段的LinkedList */ public static LinkedList getFields(Class clazz) { LinkedList fields = new LinkedList<>(); for (Class cla = clazz; cla != Object.class; cla = cla.getSuperclass()) { fields.addAll(Arrays.asList(cla.getDeclaredFields())); } return fields; } }