001    /*
002     * Created on Feb 5, 2006
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
005     * the License. You may obtain a copy of the License at
006     *
007     * http://www.apache.org/licenses/LICENSE-2.0
008     *
009     * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
010     * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
011     * specific language governing permissions and limitations under the License.
012     *
013     * Copyright @2006-2009 the original author or authors.
014     */
015    package org.fest.reflect.field;
016    
017    import static org.fest.reflect.field.Invoker.newInvoker;
018    
019    import org.fest.reflect.exception.ReflectionError;
020    
021    /**
022     * Understands the type of a static field to access using Java Reflection.
023     * <p>
024     * The following is an example of proper usage of this class:
025     * <pre>
026     *   // Retrieves the value of the static field "count"
027     *   int count = {@link org.fest.reflect.core.Reflection#staticField(String) staticField}("count").{@link StaticFieldName#ofType(Class) ofType}(int.class).{@link StaticFieldType#in(Class) in}(Person.class).{@link Invoker#get() get}();
028     *
029     *   // Sets the value of the static field "count" to 3
030     *   {@link org.fest.reflect.core.Reflection#staticField(String) staticField}("count").{@link StaticFieldName#ofType(Class) ofType}(int.class).{@link StaticFieldType#in(Class) in}(Person.class).{@link Invoker#set(Object) set}(3);
031     * </pre>
032     * </p>
033     *
034     * @param <T> the generic type of the field.
035     *
036     * @author Alex Ruiz
037     */
038    public class StaticFieldType<T> {
039    
040      static <T> StaticFieldType<T> newFieldType(String name, Class<T> type) {
041        if (type == null) throw new NullPointerException("The type of the static field to access should not be null");
042        return new StaticFieldType<T>(name, type);
043      }
044    
045      private final String name;
046      private final Class<T> type;
047    
048      StaticFieldType(String name, Class<T> type) {
049        this.name = name;
050        this.type = type;
051      }
052    
053      /**
054       * Returns a new field invoker. A field invoker is capable of accessing (read/write) the underlying field.
055       * @param target the type containing the static field of interest.
056       * @return the created field invoker.
057       * @throws NullPointerException if the given target is <code>null</code>.
058       * @throws ReflectionError if a static field with a matching name and type cannot be found.
059       */
060      public Invoker<T> in(Class<?> target) {
061        return newInvoker(name, type, target);
062      }
063    }