KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > JSX > magic > MagicClassI


1 /** (c) Brendan Macmillan 2002, licensed under GNU's GPL 2
2         (If your project is not GPL, then a fee is due - see license on website)
3     Website: http://www.csse.monash.edu.au/~bren/JSX
4     Website: http://freshmeat.net/projects/jsx
5     List (can read without subscribing, need to join to post):
6       http://groups.yahoo.com/group/JSX-ideas/messages
7         Commercial licensing enquiries only:
8             bren@objectlight.com */

9
10
11 package JSX.magic;
12 import java.io.*;
13 import java.lang.reflect.*;
14
15 public abstract class MagicClassI { // we add setFinal
16
protected static Field oscNameField;
17     protected static ObjectStreamClass osc;
18     public MagicClassI() {
19         try {
20             oscNameField = ObjectStreamClass.class.getDeclaredField( //inherited
21
"name");
22             oscNameField.setAccessible(true);
23         } catch (NoSuchFieldException JavaDoc noField) {
24             throw new InternalError JavaDoc(noField.toString());
25         }
26     }
27
28
29     abstract public Object JavaDoc newInstance(Class JavaDoc currentClass)
30             throws InvocationTargetException,
31                          NotSerializableException,
32                    IllegalAccessException JavaDoc;
33     abstract public void setObjectFieldValue(Object JavaDoc parent, Field f, Class JavaDoc type, Object JavaDoc value);
34     abstract public void setPrimitiveFieldValues(Object JavaDoc parent, Field f, Object JavaDoc value);
35
36
37 /** Two points in XMLDeserialize that need Class.forName(), and need to send it
38     * with this instead.
39     * Efficiency: Could use same instance of osc each time - Caller shouldn't
40     * rely on then being different objects.
41     **/

42     public ObjectStreamClass getOsc(String JavaDoc escapedName) throws ClassNotFoundException JavaDoc, IOException {
43         setFinal(oscNameField, osc, escapedName); //oscNameField is set statically
44
return osc;
45     }
46
47
48 //This method is never called with f==null (unless using PutFields)
49
//public, so magic can access...
50
public void setFinal(Field f, Object JavaDoc parent, Object JavaDoc value) {
51         if (f==null) return; // if using PutFields
52
if (!Modifier.isFinal(f.getModifiers())) {
53             try {
54                 f.set(parent, value);
55             } catch (IllegalAccessException JavaDoc e) {
56                 throw new InternalError JavaDoc("Unable to set '"+f+"'");
57             }
58         } else { // to set "final" fields:
59
if (f.getType().isPrimitive())
60                 setPrimitiveFieldValues(parent, f, value); // template method
61
else
62                 setObjectFieldValue(parent, f, f.getType(), value); // template method
63
}
64     }
65 }
66
Popular Tags