利用反射获取对象的数组(Array)属性

非常简单的应用,直接上代码。

0. 获取域的代码

/**
 * @author jeremysong
 */
public class AccessChecker {

    public static boolean check(Object obj, String tag) {
        if (obj == null || tag == null || tag.isEmpty()) {
            return false;
        }

        try {
            Class clz = obj.getClass();
            // Field field = clz.getField("tags");
            Field field = clz.getDeclaredField("tags");
            field.setAccessible(true);
            String[] tags = (String[]) field.get(obj);
            for (String t : tags) {
                if (tag.equals(t)) return true;
            }
        } catch (NoSuchFieldException e) {
            System.out.println("指定对象无tags属性");
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            System.out.println("获取不到指定对象的tags属性");
            e.printStackTrace();
        }

        return false;
    }
}

1. 测试用例

public class Worker {

    private String name;
    private String[] tags;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String[] getTags() {
        return tags;
    }

    public void setTags(String[] tags) {
        this.tags = tags;
    }
}
import org.junit.Assert;
import org.junit.Test;

public class AccessCheckerTester {

    @Test
    public void testCheck1() {
        Worker worker = new Worker();
        worker.setName("jeremysong");
        worker.setTags(new String[]{"person", "male", "developer"});
        Assert.assertTrue(AccessChecker.check(worker, "person"));
    }

    @Test
    public void testCheck2() {
        Worker worker = new Worker();
        worker.setName("jeremysong");
        worker.setTags(new String[]{"person", "male", "developer"});
        Assert.assertFalse(AccessChecker.check(worker, "teacher"));
    }
}

2. 单元测试用例执行结果

利用反射获取对象的数组(Array)属性_第1张图片

你可能感兴趣的:(java,反射)