KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > wings > util > PropertyAccessor


1 /*
2  * $Id: PropertyAccessor.java,v 1.4 2004/12/01 07:54:30 hengels Exp $
3  * Copyright 2000,2005 wingS development team.
4  *
5  * This file is part of wingS (http://www.j-wings.org).
6  *
7  * wingS is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU Lesser General Public License
9  * as published by the Free Software Foundation; either version 2.1
10  * of the License, or (at your option) any later version.
11  *
12  * Please see COPYING for the complete licence.
13  */

14 package org.wings.util;
15
16 import java.lang.reflect.Method JavaDoc;
17
18 /**
19  * little helper class to access properties via introspection. Quick
20  * hack, not yet implemneted completely.
21  */

22 public class PropertyAccessor {
23     /**
24      * determines.
25      */

26     public static boolean hasProperty(Object JavaDoc o, String JavaDoc name) {
27         try {
28             Method JavaDoc[] m = o.getClass().getMethods();
29             String JavaDoc setterName = "set" + capitalize(name);
30             for (int i = 0; i < m.length; ++i) {
31                 if (m[i].getParameterTypes().length == 1
32                         && m[i].getName().equals(setterName)) {
33                     // (maybe check, whether there is a getter here).
34
return true;
35                 }
36             }
37         } catch (Exception JavaDoc e) {}
38         return false;
39     }
40
41
42     public static void setProperty(Object JavaDoc o, String JavaDoc name, Object JavaDoc value) {
43         try {
44             Method JavaDoc[] m = o.getClass().getMethods();
45             String JavaDoc setterName = "set" + capitalize(name);
46             for (int i = 0; i < m.length; ++i) {
47                 if (m[i].getParameterTypes().length == 1
48                         && m[i].getName().equals(setterName)
49                         && (value == null
50                         || (m[i].getParameterTypes()[0]
51                         .isAssignableFrom(value.getClass())))) {
52                     m[i].invoke(o, new Object JavaDoc[]{value});
53                 }
54             }
55         } catch (Exception JavaDoc e) {}
56     }
57
58
59     public static void getProperty(Object JavaDoc o, String JavaDoc name, Object JavaDoc value) {
60         // not yet implemented.
61
}
62
63     /**
64      * captialize a string. A String 'foo' becomes 'Foo'. Used to
65      * derive names of getters from the property name.
66      */

67     private static String JavaDoc capitalize(String JavaDoc s) {
68         s = s.trim();
69         return s.substring(0, 1).toUpperCase() + s.substring(1);
70     }
71 }
72
73
74
Popular Tags