001 /*
002 * Created on Jan 24, 2009
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 @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 import org.fest.reflect.reference.TypeRef;
021
022 /**
023 * Understands the type of a field to access using Java Reflection. This implementation supports Java generics.
024 * <p>
025 * The following is an example of proper usage of this class:
026 * <pre>
027 * // Retrieves the value of the field "powers"
028 * List<String> powers = {@link org.fest.reflect.core.Reflection#field(String) field}("powers").{@link FieldName#ofType(TypeRef) ofType}(new {@link TypeRef TypeRef}<List<String>>() {}).{@link #in(Object) in}(jedi).{@link Invoker#get() get}();
029 *
030 * // Sets the value of the field "powers"
031 * List<String> powers = new ArrayList<String>();
032 * powers.add("heal");
033 * {@link org.fest.reflect.core.Reflection#field(String) field}("powers").{@link FieldName#ofType(TypeRef) ofType}(new {@link TypeRef TypeRef}<List<String>>() {}).{@link #in(Object) in}(jedi).{@link Invoker#set(Object) set}(powers);
034 * </pre>
035 * </p>
036 *
037 * @param <T> the generic type of the field.
038 *
039 * @author Alex Ruiz
040 *
041 * @since 1.1
042 */
043 public class FieldTypeRef<T> {
044
045 static <T> FieldTypeRef<T> newFieldTypeRef(String name, TypeRef<T> type) {
046 if (type == null)
047 throw new NullPointerException("The type reference of the field to access should not be null");
048 return new FieldTypeRef<T>(name, type);
049 }
050
051 private final String name;
052 private final TypeRef<T> type;
053
054 private FieldTypeRef(String name, TypeRef<T> type) {
055 this.name = name;
056 this.type = type;
057 }
058
059 /**
060 * Returns a new field invoker. A field invoker is capable of accessing (read/write) the underlying field.
061 * @param target the object containing the field of interest.
062 * @return the created field invoker.
063 * @throws NullPointerException if the given target is <code>null</code>.
064 * @throws ReflectionError if a field with a matching name and type cannot be found.
065 */
066 public Invoker<T> in(Object target) {
067 return newInvoker(name, type, target);
068 }
069 }