com.tencent.matrix.javalib.util.ReflectUtil Maven / Gradle / Ivy
/*
* Tencent is pleased to support the open source community by making wechat-matrix available.
* Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.tencent.matrix.javalib.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Created by caichongyang on 17/7/4.
*/
public final class ReflectUtil {
public static Field getDeclaredFieldRecursive(Object clazz, String fieldName) throws NoSuchFieldException, ClassNotFoundException {
Class> realClazz = null;
if (clazz instanceof String) {
realClazz = Class.forName((String) clazz);
} else if (clazz instanceof Class) {
realClazz = (Class>) clazz;
} else {
throw new IllegalArgumentException("Illegal clazz type: " + clazz.getClass());
}
Class> currClazz = realClazz;
while (true) {
try {
Field field = currClazz.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
if (currClazz.equals(Object.class)) {
throw e;
}
currClazz = currClazz.getSuperclass();
}
}
}
public static Method getDeclaredMethodRecursive(Object clazz, String methodName, Class>... argTypes) throws NoSuchMethodException, ClassNotFoundException {
Class> realClazz = null;
if (clazz instanceof String) {
realClazz = Class.forName((String) clazz);
} else if (clazz instanceof Class) {
realClazz = (Class>) clazz;
} else {
throw new IllegalArgumentException("Illegal clazz type: " + clazz.getClass());
}
Class> currClazz = realClazz;
while (true) {
try {
Method method = currClazz.getDeclaredMethod(methodName);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException e) {
if (currClazz.equals(Object.class)) {
throw e;
}
currClazz = currClazz.getSuperclass();
}
}
}
private ReflectUtil() {
throw new UnsupportedOperationException();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy