aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/junit/runners/model/FrameworkField.java
blob: ea2b16f8c4aefe8739bd9c343d3590bf1d2cd163 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package org.junit.runners.model;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

import org.junit.runners.BlockJUnit4ClassRunner;

/**
 * Represents a field on a test class (currently used only for Rules in
 * {@link BlockJUnit4ClassRunner}, but custom runners can make other uses)
 *
 * @since 4.7
 */
public class FrameworkField extends FrameworkMember<FrameworkField> {
    private final Field field;

    /**
     * Returns a new {@code FrameworkField} for {@code field}.
     *
     * <p>Access relaxed to {@code public} since version 4.13.1.
     */
    public FrameworkField(Field field) {
        if (field == null) {
            throw new NullPointerException(
                    "FrameworkField cannot be created without an underlying field.");
        }
        this.field = field;

        if (isPublic()) {
            // This field could be a public field in a package-scope base class
            try {
                field.setAccessible(true);
            } catch (SecurityException e) {
                // We may get an IllegalAccessException when we try to access the field
            }
        }
    }

    @Override
    public String getName() {
        return getField().getName();
    }

    public Annotation[] getAnnotations() {
        return field.getAnnotations();
    }

    public <T extends Annotation> T getAnnotation(Class<T> annotationType) {
        return field.getAnnotation(annotationType);
    }

    @Override
    public boolean isShadowedBy(FrameworkField otherMember) {
        return otherMember.getName().equals(getName());
    }

    @Override
    boolean isBridgeMethod() {
        return false;
    }

    @Override
    protected int getModifiers() {
        return field.getModifiers();
    }

    /**
     * @return the underlying java Field
     */
    public Field getField() {
        return field;
    }

    /**
     * @return the underlying Java Field type
     * @see java.lang.reflect.Field#getType()
     */
    @Override
    public Class<?> getType() {
        return field.getType();
    }
    
    @Override
    public Class<?> getDeclaringClass() {
        return field.getDeclaringClass();
    }

    /**
     * Attempts to retrieve the value of this field on {@code target}
     */
    public Object get(Object target) throws IllegalArgumentException, IllegalAccessException {
        return field.get(target);
    }

    @Override
    public String toString() {
        return field.toString();
    }
}