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
022 /**
023 * Understands the type of a property to access using Bean Instrospection.
024 * <p>
025 * The following is an example of proper usage of this class:
026 * <pre>
027 * // Retrieves the value of the property "name"
028 * String name = {@link org.fest.reflect.core.Reflection#property(String) property}("name").{@link PropertyName#ofType(Class) ofType}(String.class).{@link PropertyType#in(Object) in}(person).{@link Invoker#get() get}();
029 *
030 * // Sets the value of the property "name" to "Yoda"
031 * {@link org.fest.reflect.core.Reflection#property(String) property}("name").{@link PropertyName#ofType(Class) ofType}(String.class).{@link PropertyType#in(Object) in}(person).{@link Invoker#set(Object) set}("Yoda");
032 * </pre>
033 * </p>
034 *
035 * @param <T> the generic type of the property.
036 *
037 * @author Alex Ruiz
038 *
039 * @since 1.2
040 */
041 public class PropertyType<T> {
042
043 static <T> PropertyType<T> newPropertyType(String name, Class<T> type) {
044 if (type == null) throw new NullPointerException("The type of the property to access should not be null");
045 return new PropertyType<T>(name, type);
046 }
047
048 private final String name;
049 private final Class<T> type;
050
051 private PropertyType(String name, Class<T> type) {
052 this.name = name;
053 this.type = type;
054 }
055
056 /**
057 * Returns a new property invoker. A property invoker is capable of accessing (read/write) the underlying property.
058 * @param target the object containing the property of interest.
059 * @return the created property invoker.
060 * @throws NullPointerException if the given target is <code>null</code>.
061 * @throws ReflectionError if a property with a matching name and type cannot be found.
062 */
063 public Invoker<T> in(Object target) {
064 if (target == null) throw new NullPointerException("Target should not be null");
065 return newInvoker(name, type, target);
066 }
067 }