001 /*
002 * Created on Nov 23, 2009
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with 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
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 *
014 * Copyright @2009 the original author or authors.
015 */
016 package org.fest.reflect.beanproperty;
017
018 import static org.fest.reflect.beanproperty.Invoker.newInvoker;
019
020 import org.fest.reflect.exception.ReflectionError;
021 import org.fest.reflect.reference.TypeRef;
022
023 /**
024 * Understands the type of a property to access using Bean Instrospection. This implementation supports Java generics.
025 * <p>
026 * The following is an example of proper usage of this class:
027 * <pre>
028 * // Retrieves the value of the property "powers"
029 * List<String> powers = {@link org.fest.reflect.core.Reflection#property(String) property}("powers").{@link PropertyName#ofType(TypeRef) ofType}(new {@link TypeRef TypeRef}<List<String>>() {}).{@link #in(Object) in}(jedi).{@link Invoker#get() get}();
030 *
031 * // Sets the value of the property "powers"
032 * List<String> powers = new ArrayList<String>();
033 * powers.add("heal");
034 * {@link org.fest.reflect.core.Reflection#property(String) property}("powers").{@link PropertyName#ofType(TypeRef) ofType}(new {@link TypeRef TypeRef}<List<String>>() {}).{@link #in(Object) in}(jedi).{@link Invoker#set(Object) set}(powers);
035 * </pre>
036 * </p>
037 *
038 * @param <T> the generic type of the property.
039 *
040 * @author Alex Ruiz
041 *
042 * @since 1.2
043 */
044 public class PropertyTypeRef<T> {
045
046 static <T> PropertyTypeRef<T> newPropertyTypeRef(String name, TypeRef<T> type) {
047 if (type == null) throw new NullPointerException("The type reference of the property to access should not be null");
048 return new PropertyTypeRef<T>(name, type);
049 }
050
051 private final TypeRef<T> type;
052 private final String name;
053
054 private PropertyTypeRef(String name, TypeRef<T> type) {
055 this.name = name;
056 this.type = type;
057 }
058
059 /**
060 * Returns a new property invoker. A property invoker is capable of accessing (read/write) the underlying property.
061 * @param target the object containing the property of interest.
062 * @return the created property invoker.
063 * @throws NullPointerException if the given target is <code>null</code>.
064 * @throws ReflectionError if a property 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 }