You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
chat-room/util/ReflectUtils.java

80 lines
2.5 KiB

/*
* 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 <a href="mailto:kobe524348@gmail.com">黄钰朝</a>
* @program XHotel
* @description 用于反射的工具
* @date 2019-04-20 02:28
*/
public class ReflectUtils {
/**
* 获取指定对象的所有方法(包括其父类的方法)
*
* @param obj 需要获取方法的实例对象
* @return 返回一个包含所有方法的LinkedList
*/
public static LinkedList<Method> getMethods(Object obj) {
return getMethods(obj.getClass());
}
/**
* 获取指定类的所有方法(包括其父类的方法)
*
* @param clazz 需要获取方法的类
* @return 返回一个包含所有方法的LinkedList
*/
public static LinkedList<Method> getMethods(Class clazz) {
LinkedList<Method> 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<Field> getFields(Object obj) {
return getFields(obj.getClass());
}
/**
* 获取指定类的所有字段(包括其父类的字段)
*
* @param clazz 需要获取字段的类
* @return 返回一个包含所有字段的LinkedList
*/
public static LinkedList<Field> getFields(Class clazz) {
LinkedList<Field> fields = new LinkedList<>();
for (Class cla = clazz; cla != Object.class; cla = cla.getSuperclass()) {
fields.addAll(Arrays.asList(cla.getDeclaredFields()));
}
return fields;
}
}