KickJava   Java API By Example, From Geeks To Geeks.

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


1 // ============================================================================
2
// $Id: SetProperty.java,v 1.14 2006/08/05 21:36:16 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.Method JavaDoc;
37 import java.text.MessageFormat JavaDoc;
38 import net.sf.jga.fn.BinaryFunctor;
39 import net.sf.jga.fn.EvaluationException;
40
41 /**
42  * Binary Functor that sets the named property of the first argument to the
43  * value. The property name and type are set at construction. The return
44  * value will be that which the argument's property setter method returns
45  * (generally either null or the old value).
46  * <p>
47  * Note that declaring the return type incorrectly can result in
48  * ClassCastExceptions being thrown when the functor is invoked: the compiler
49  * cannot check the return type of a reflectively loaded method.
50  * <p>
51  * Copyright &copy; 2002-2005 David A. Hall
52  *
53  * @author <a HREF="mailto:davidahall@users.sourceforge.net">David A. Hall</a>
54  **/

55
56 // NOTE: compiling this class yields one unchecked cast warning. It is really
57
// up to the user to declare this class properly (the return type must be
58
// correctly specified)
59

60 public class SetProperty<T,R> extends BinaryFunctor<T,R,R> {
61
62     static final long serialVersionUID = 5305970242256716550L;
63     
64     // The property class, used to find the correct Method using reflection
65
private Class JavaDoc<R> _propClass;
66
67     // The name of the property (without the leading 'set').
68
private String JavaDoc _propName;
69
70     // The name of the setter method (same as _propName, but with 'set' prefix)
71
private String JavaDoc _methName;
72
73     // The method to invoke
74
private transient Method JavaDoc _meth;
75
76     /**
77      * Builds a SetProperty that will return the value of the named property
78      * of an instance of type argType. The property will be of type propType.
79      * @throws IllegalArgumentException if either argument is omitted, or if
80      * there is no such setter method in type argType.
81      */

82     public SetProperty(Class JavaDoc<T> argType, String JavaDoc propName, Class JavaDoc<R> propType) {
83         if (propName == null || propName.length() == 0) {
84             throw new IllegalArgumentException JavaDoc("Must supply property name");
85         }
86         if (propType == null) {
87             throw new IllegalArgumentException JavaDoc("Must supply property type");
88         }
89         
90         if (propName.startsWith("set")) {
91             _methName = propName;
92             _propName = propName.substring(3);
93         }
94         else {
95             _propName = propName;
96             _methName = "set" + propName;
97         }
98         
99         _propClass = propType;
100         
101         try {
102             Class JavaDoc[] car = new Class JavaDoc[]{propType};
103             _meth = argType.getMethod(_methName, car);
104         }
105         catch (NoSuchMethodException JavaDoc x) {
106             String JavaDoc msg = "class {0} does not have property \"{1}\" of type {2}";
107             Object JavaDoc[] args = new Object JavaDoc[]{ argType.getName(), propName, propType.getName() };
108             IllegalArgumentException JavaDoc iax =
109                 new IllegalArgumentException JavaDoc(MessageFormat.format(msg,args));
110             iax.initCause(x);
111             throw iax;
112         }
113     }
114     
115
116     /**
117      * Returns the name of the property that this functor sets.
118      */

119     public String JavaDoc getPropertyName() {
120         return _propName;
121     }
122
123     // Binary interface
124

125     /**
126      * Sets the designated property of the argument to the given value. When
127      * the property's setter method returns a value, then this functor will
128      * return it (otherwise it will return null).
129      * <p>
130      * @return the value returned by the designated property's setter method:
131      * generally it is null, but in some cases it might be the old value
132      * @throws EvaluationException if the argument does not have the designated
133      * public property, or if it is accept the given value.
134      */

135     public R fn(T arg, R val) {
136         try {
137             // @SuppressWarnings
138
// There's nothing we can do about this other than warn the users
139
// to make sure that they don't use an inappropriate return type
140
R ret = (R) getMethod(arg).invoke(arg, new Object JavaDoc[] {val});
141             return ret;
142         }
143         catch (ClassCastException JavaDoc x) {
144             String JavaDoc msg = "{0}.{1} returns type {2}";
145             Method JavaDoc m = getMethod(arg);
146             Object JavaDoc[] args = new Object JavaDoc[]{ arg.getClass().getName(), m.getName(),
147                                           m.getReturnType().getName() };
148             throw new EvaluationException(MessageFormat.format(msg,args), x);
149         }
150         catch (IllegalAccessException JavaDoc x) {
151             String JavaDoc msg = "{0}.{1} is not accessible";
152             Object JavaDoc[] args = new Object JavaDoc[]{ arg.getClass().getName(), getMethod(arg).getName()};
153             throw new EvaluationException(MessageFormat.format(msg,args), x);
154         }
155         catch (InvocationTargetException JavaDoc x) {
156             String JavaDoc msg = "{0}.{1}({2}) failed : "+x.getMessage();
157             Object JavaDoc[] args = new Object JavaDoc[]{ arg.getClass().getName(), getMethod(arg).getName(), val};
158             throw new EvaluationException(MessageFormat.format(msg,args), x);
159         }
160     }
161
162     private Method JavaDoc getMethod(T arg) {
163         if (_meth == null) {
164             try {
165                 Class JavaDoc[] car = new Class JavaDoc[]{_propClass}; //new Class[]{R}
166
_meth = arg.getClass().getMethod(_methName, car);
167             }
168             catch (NoSuchMethodException JavaDoc x) {
169                 throw new EvaluationException(x);}
170         }
171
172         return _meth;
173     }
174
175     /**
176      * Calls the Visitor's <code>visit(SetProperty)</code> method, if it
177      * implements the nested Visitor interface.
178      */

179     public void accept(net.sf.jga.fn.Visitor v) {
180         if (v instanceof SetProperty.Visitor)
181             ((SetProperty.Visitor)v).visit(this);
182         else
183             v.visit(this);
184     }
185     
186     // Object overrides
187

188     public String JavaDoc toString() {
189         return "SetProperty("+_methName+")";
190     }
191     
192     // AcyclicVisitor
193

194     /**
195      * Interface for classes that may interpret a <b>SetProperty</b>
196      * function.
197      */

198     public interface Visitor extends net.sf.jga.fn.Visitor {
199         public void visit(SetProperty host);
200     }
201 }
202
Popular Tags