KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > jga > fn > property > GetField


1 // ============================================================================
2
// $Id: GetField.java,v 1.11 2006/08/05 21:34:32 davidahall Exp $
3
// Copyright (c) 2002-2005 David A. Hall
4
// ============================================================================
5
// The contents of this file are subject to the Common Development and
6
// Distribution License (CDDL), Version 1.0 (the License); you may not use this
7
// file except in compliance with the License. You should have received a copy
8
// of the the License along with this file: if not, a copy of the License is
9
// available from Sun Microsystems, Inc.
10
//
11
// http://www.sun.com/cddl/cddl.html
12
//
13
// From time to time, the license steward (initially Sun Microsystems, Inc.) may
14
// publish revised and/or new versions of the License. You may not use,
15
// distribute, or otherwise make this file available under subsequent versions
16
// of the License.
17
//
18
// Alternatively, the contents of this file may be used under the terms of the
19
// GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which
20
// case the provisions of the LGPL are applicable instead of those above. If you
21
// wish to allow use of your version of this file only under the terms of the
22
// LGPL, and not to allow others to use your version of this file under the
23
// terms of the CDDL, indicate your decision by deleting the provisions above
24
// and replace them with the notice and other provisions required by the LGPL.
25
// If you do not delete the provisions above, a recipient may use your version
26
// of this file under the terms of either the CDDL or the LGPL.
27
//
28
// This library is distributed in the hope that it will be useful,
29
// but WITHOUT ANY WARRANTY; without even the implied warranty of
30
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
31
// ============================================================================
32

33 package net.sf.jga.fn.property;
34
35 import java.lang.reflect.InvocationTargetException JavaDoc;
36 import java.lang.reflect.Field JavaDoc;
37 import java.text.MessageFormat JavaDoc;
38 import net.sf.jga.fn.EvaluationException;
39 import net.sf.jga.fn.UnaryFunctor;
40
41 /**
42  * Unary Functor that returns the value of the named field for the argument.
43  * The field name and type are set at construction.
44  * <p>
45  * Copyright &copy; 2002-2005 David A. Hall
46  *
47  * @author <a HREF="mailto:davidahall@users.sourceforge.net">David A. Hall</a>
48  **/

49
50 public class GetField<T,R> extends UnaryFunctor<T,R> {
51     
52     static final long serialVersionUID = 5733484457689881481L;
53
54     // The name of the field to be retrieved.
55
private String JavaDoc _fieldName;
56
57     // The class from which the field is retrieved.
58
private Class JavaDoc<T> _argtype;
59     
60     // The Field whose valus is returned
61
private transient Field JavaDoc _field;
62
63     /**
64      * Builds a GetField for the given field
65      * @throws IllegalArgumentException if the field is null, or is not a field
66      * of the given class
67      */

68     public GetField(Field JavaDoc field) {
69         if (field == null) {
70             throw new IllegalArgumentException JavaDoc("Must supply field");
71         }
72
73         _field = field;
74         _fieldName = field.getName();
75             // @SuppressWarnings
76
// There's nothing we can do about this other than warn the users
77
// to make sure that they don't use an inappropriate argument type
78
_argtype = (Class JavaDoc<T>) field.getDeclaringClass();
79     }
80     
81     /**
82      * Builds a GetField for the given field
83      * @throws IllegalArgumentException if the field is null, or is not a field
84      * of the given class
85      */

86     public GetField(Class JavaDoc<T> argclass, Field JavaDoc field) {
87         if (field == null) {
88             throw new IllegalArgumentException JavaDoc("Must supply field");
89         }
90
91         if (!field.getDeclaringClass().isAssignableFrom(argclass)) {
92             throw new IllegalArgumentException JavaDoc(buildNoSuchFieldMessage(field.getName(), argclass));
93         }
94         
95         _field = field;
96         _fieldName = field.getName();
97         _argtype = argclass;
98     }
99
100     /**
101      * Builds a GetField for the given field, using the given class to
102      * find the desired field.
103      * @throws IllegalArgumentException if the field name is null or empty,
104      *
105      */

106     public GetField(Class JavaDoc<T> argclass, String JavaDoc fieldName) {
107         if (fieldName == null || fieldName.length() == 0) {
108             throw new IllegalArgumentException JavaDoc("Must supply field name");
109         }
110
111         _fieldName = fieldName;
112         _argtype = argclass;
113         
114         try {
115             _field = argclass.getField(_fieldName);
116         }
117         catch (NoSuchFieldException JavaDoc x) {
118             IllegalArgumentException JavaDoc iax =
119                 new IllegalArgumentException JavaDoc(buildNoSuchFieldMessage(fieldName, argclass));
120             
121             iax.initCause(x);
122             throw iax;
123         }
124     }
125
126     /**
127      * Returns the class on which the field is retrieved.
128      */

129     // UNTESTED
130
public Class JavaDoc<T> getObjectType() {
131         return _argtype;
132     }
133
134     /**
135      * Returns the name of the field that this functor retrieves.
136      */

137     public String JavaDoc getFieldName() {
138         return _fieldName;
139     }
140
141     /**
142      * Returns the type of field that this functor retrieves.
143      */

144
145     public Class JavaDoc<R> getFieldType() {
146         return (Class JavaDoc<R>) _field.getType();
147     }
148
149     
150     /**
151      * Lazily loads the Field object.
152      */

153     
154     // Instances of Reflection classes are not serializable, so this must be loaded lazily
155
// in case this object was read from a stream (the first time the functor is invoked,
156
// the field object will be instantiated)
157

158     public synchronized Field JavaDoc getField() throws NoSuchFieldException JavaDoc {
159         if (_field == null)
160             _field = _argtype.getField(_fieldName);
161
162         return _field;
163     }
164
165     // Unary interface
166

167     /**
168      * Returns the value of the designated field of the argument
169      * @return the value of the designated field of the argument
170      * @throws EvaluationException if the argument does not have the designated
171      * public field, or if it is not of the correct type.
172      */

173     public R fn(T arg) {
174         try {
175             // @SuppressWarnings("unchecked")
176
// There's nothing we can do about this other than warn the users
177
// to make sure that they don't use an inappropriate return type
178
R val = (R) getField().get(arg);
179             return val;
180         }
181         catch (NoSuchFieldException JavaDoc x) {
182             throw new EvaluationException(buildNoSuchFieldMessage(_fieldName, _argtype));
183         }
184         catch (ClassCastException JavaDoc x) {
185             String JavaDoc msg = "{0}.{1} is of type {2}";
186             Object JavaDoc[] args = new Object JavaDoc[]{ arg.getClass().getName(), _field.getName(),
187                                           _field.getType().getName() };
188             throw new EvaluationException(MessageFormat.format(msg,args), x);
189         }
190         catch (IllegalAccessException JavaDoc x) {
191             String JavaDoc msg = "{0}.{1} is not accessible";
192             Object JavaDoc[] args = new Object JavaDoc[]{ _argtype.getName(), _fieldName};
193             throw new EvaluationException(MessageFormat.format(msg,args), x);
194         }
195     }
196
197
198     /**
199      */

200     private String JavaDoc buildNoSuchFieldMessage(String JavaDoc fieldname, Class JavaDoc clasz) {
201         String JavaDoc msg = "class {0} does not have field {1}";
202         Object JavaDoc[] args = new Object JavaDoc[]{ clasz.getName(), fieldname };
203         return MessageFormat.format(msg,args);
204     }
205
206     /**
207      * Calls the Visitor's <code>visit(GetField)</code> field, if it
208      * implements the nested Visitor interface.
209      */

210     public void accept(net.sf.jga.fn.Visitor v) {
211         if (v instanceof GetField.Visitor)
212             ((GetField.Visitor)v).visit(this);
213         else
214             v.visit(this);
215     }
216     
217     // Object overrides
218

219     public String JavaDoc toString() {
220         return "GetField["+_argtype.getName()+"."+_fieldName+"]";
221     }
222     
223    // AcyclicVisitor
224

225     /**
226      * Interface for classes that may interpret a <b>GetField</b>
227      * function.
228      */

229     public interface Visitor extends net.sf.jga.fn.Visitor {
230         public void visit(GetField host);
231     }
232 }
233
Popular Tags