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 /** 019 * Returns a new {@code FrameworkField} for {@code field}. 020 * 021 * <p>Access relaxed to {@code public} since version 4.13.1. 022 */ 023 public FrameworkField(Field field) { 024 if (field == null) { 025 throw new NullPointerException( 026 "FrameworkField cannot be created without an underlying field."); 027 } 028 this.field = field; 029 030 if (isPublic()) { 031 // This field could be a public field in a package-scope base class 032 try { 033 field.setAccessible(true); 034 } catch (SecurityException e) { 035 // We may get an IllegalAccessException when we try to access the field 036 } 037 } 038 } 039 040 @Override 041 public String getName() { 042 return getField().getName(); 043 } 044 045 public Annotation[] getAnnotations() { 046 return field.getAnnotations(); 047 } 048 049 public <T extends Annotation> T getAnnotation(Class<T> annotationType) { 050 return field.getAnnotation(annotationType); 051 } 052 053 @Override 054 public boolean isShadowedBy(FrameworkField otherMember) { 055 return otherMember.getName().equals(getName()); 056 } 057 058 @Override 059 boolean isBridgeMethod() { 060 return false; 061 } 062 063 @Override 064 protected int getModifiers() { 065 return field.getModifiers(); 066 } 067 068 /** 069 * @return the underlying java Field 070 */ 071 public Field getField() { 072 return field; 073 } 074 075 /** 076 * @return the underlying Java Field type 077 * @see java.lang.reflect.Field#getType() 078 */ 079 @Override 080 public Class<?> getType() { 081 return field.getType(); 082 } 083 084 @Override 085 public Class<?> getDeclaringClass() { 086 return field.getDeclaringClass(); 087 } 088 089 /** 090 * Attempts to retrieve the value of this field on {@code target} 091 */ 092 public Object get(Object target) throws IllegalArgumentException, IllegalAccessException { 093 return field.get(target); 094 } 095 096 @Override 097 public String toString() { 098 return field.toString(); 099 } 100 }