001package org.javasimon.console.reflect;
002
003import java.lang.reflect.InvocationTargetException;
004import java.lang.reflect.Method;
005
006/**
007 * Property getter (in the Java Bean terminalogy) with sub-type management.
008 * Serves as a helper to get Getter methods from given class and use them to get
009 * values from given instance
010 *
011 * @author gquintana
012 */
013public class Getter<T> {
014
015        /**
016         * Property name
017         */
018        private final String name;
019        /**
020         * Property type
021         */
022        private final Class<T> type;
023        /**
024         * Property sub type
025         */
026        private final String subType;
027        /**
028         * Property getter method
029         */
030        private final Method method;
031        /**
032         * Hidden constructor use factory methods instead
033         */
034        Getter(String name, Class<T> type, String subType, Method method) {
035                this.name = name;
036                this.type = type;
037                this.method = method;
038                this.subType = subType;
039        }
040        /**
041         * Getter method
042         */
043        public Method getMethod() {
044                return method;
045        }
046        /**
047         * Property name
048         */
049        public String getName() {
050                return name;
051        }
052        /**
053         * Property type
054         */
055        public Class<T> getType() {
056                return type;
057        }
058        /**
059         * Property sub type
060         */
061        public String getSubType() {
062                return subType;
063        }
064
065        /**
066         * Get value from source object using getter method
067         * @param source Source object
068         * @return Value
069         */
070        public T get(Object source) {
071                try {
072                        if (!method.isAccessible()) {
073                                method.setAccessible(true);
074                        }
075                        @SuppressWarnings("unchecked")
076                        T value=(T) method.invoke(source);
077                        return value;
078                } catch (IllegalAccessException illegalAccessException) {
079                        return null;
080                } catch (IllegalArgumentException illegalArgumentException) {
081                        return null;
082                } catch (InvocationTargetException invocationTargetException) {
083                        return null;
084                }
085        }
086}