001 /*
002 * Created on Aug 17, 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 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 field "name"
027 * String name = {@link org.fest.reflect.core.Reflection#field(String) field}("name").{@link FieldName#ofType(Class) ofType}(String.class).{@link FieldType#in(Object) in}(person).{@link Invoker#get() get}();
028 *
029 * // Sets the value of the field "name" to "Yoda"
030 * {@link org.fest.reflect.core.Reflection#field(String) field}("name").{@link FieldName#ofType(Class) ofType}(String.class).{@link FieldType#in(Object) in}(person).{@link Invoker#set(Object) set}("Yoda");
031 * </pre>
032 * </p>
033 *
034 * @param <T> the generic type of the field.
035 *
036 * @author Alex Ruiz
037 */
038 public class FieldType<T> {
039
040 static <T> FieldType<T> newFieldType(String name, Class<T> type) {
041 if (type == null) throw new NullPointerException("The type of the field to access should not be null");
042 return new FieldType<T>(name, type);
043 }
044
045 private final String name;
046 private final Class<T> type;
047
048 private FieldType(String name, Class<T> type) {
049 this.name = name;
050 this.type = type;
051 }
052
053 /**
054 * Returns a new field access invoker, capable of accessing (read/write) the underlying field.
055 * @param target the object containing the field of interest.
056 * @return the created field access invoker.
057 * @throws NullPointerException if the given target is <code>null</code>.
058 * @throws ReflectionError if a field with a matching name and type cannot be found.
059 */
060 public Invoker<T> in(Object target) {
061 return newInvoker(name, type, target);
062 }
063 }