Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Field;

public class Main {
    public static Object getDeclaredField(Object obj, Class<?> cls, String fieldName) throws NoSuchFieldException {
        if (obj == null || cls == null || fieldName == null) {
            throw new IllegalArgumentException("parameter can not be null!");
        }
        try {
            Field declaredField = cls.getDeclaredField(fieldName);
            declaredField.setAccessible(true);
            return declaredField.get(obj);
        } catch (Exception e) {
            throw new NoSuchFieldException(fieldName);
        }
    }

    public static Object getDeclaredField(String classame, String fieldName) throws NoSuchFieldException {
        if (classame == null || fieldName == null) {
            throw new IllegalArgumentException("parameter can not be null!");
        }
        try {
            Class cls = Class.forName(classame);
            return getSupperField(cls, cls, fieldName);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("className not found");
        }
    }

    private static Object getSupperField(Object obj, Class<?> cls, String fieldName) throws NoSuchFieldException {
        Class superclass = cls.getSuperclass();
        while (superclass != null) {
            try {
                return getDeclaredField(obj, superclass, fieldName);
            } catch (NoSuchFieldException e) {
                try {
                    superclass = superclass.getSuperclass();
                } catch (Exception e2) {
                    superclass = null;
                }
            }
        }
        throw new NoSuchFieldException(fieldName);
    }
}