001 package org.junit.runners.model;
002
003 import java.lang.annotation.Annotation;
004 import java.lang.reflect.Field;
005 import java.util.List;
006
007 import org.junit.runners.BlockJUnit4ClassRunner;
008
009 /**
010 * Represents a field on a test class (currently used only for Rules in
011 * {@link BlockJUnit4ClassRunner}, but custom runners can make other uses)
012 *
013 * @since 4.7
014 */
015 public class FrameworkField extends FrameworkMember<FrameworkField> {
016 private final Field field;
017
018 FrameworkField(Field field) {
019 if (field == null) {
020 throw new NullPointerException(
021 "FrameworkField cannot be created without an underlying field.");
022 }
023 this.field = field;
024
025 if (isPublic()) {
026 // This field could be a public field in a package-scope base class
027 try {
028 field.setAccessible(true);
029 } catch (SecurityException e) {
030 // We may get an IllegalAccessException when we try to access the field
031 }
032 }
033 }
034
035 @Override
036 public String getName() {
037 return getField().getName();
038 }
039
040 public Annotation[] getAnnotations() {
041 return field.getAnnotations();
042 }
043
044 public <T extends Annotation> T getAnnotation(Class<T> annotationType) {
045 return field.getAnnotation(annotationType);
046 }
047
048 @Override
049 public boolean isShadowedBy(FrameworkField otherMember) {
050 return otherMember.getName().equals(getName());
051 }
052
053 @Override
054 boolean isBridgeMethod() {
055 return false;
056 }
057
058 @Override
059 protected int getModifiers() {
060 return field.getModifiers();
061 }
062
063 /**
064 * @return the underlying java Field
065 */
066 public Field getField() {
067 return field;
068 }
069
070 /**
071 * @return the underlying Java Field type
072 * @see java.lang.reflect.Field#getType()
073 */
074 @Override
075 public Class<?> getType() {
076 return field.getType();
077 }
078
079 @Override
080 public Class<?> getDeclaringClass() {
081 return field.getDeclaringClass();
082 }
083
084 /**
085 * Attempts to retrieve the value of this field on {@code target}
086 */
087 public Object get(Object target) throws IllegalArgumentException, IllegalAccessException {
088 return field.get(target);
089 }
090
091 @Override
092 public String toString() {
093 return field.toString();
094 }
095 }