1 | // Copyright 2004-2007 Jean-Francois Poilpret |
2 | // |
3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
4 | // you may not use this file except in compliance with the License. |
5 | // You may obtain a copy of the License at |
6 | // |
7 | // http://www.apache.org/licenses/LICENSE-2.0 |
8 | // |
9 | // Unless required by applicable law or agreed to in writing, software |
10 | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | // See the License for the specific language governing permissions and |
13 | // limitations under the License. |
14 | |
15 | package net.sourceforge.hiveutils.util; |
16 | |
17 | import java.util.ArrayList; |
18 | import java.util.List; |
19 | |
20 | /** |
21 | * Utility class to check if the class of an object is a subclass of one class |
22 | * in a list. |
23 | * |
24 | * @author Jean-Francois Poilpret |
25 | */ |
26 | public class ClassMatcher |
27 | { |
28 | /** |
29 | * Add a class to the list, associated with a value. |
30 | * @param clazz Class to be added to the list |
31 | * @param value value to be returned (by <code>get()</code> when the passed |
32 | * object is an instance of that class. |
33 | */ |
34 | synchronized public void put(Class clazz, Object value) |
35 | { |
36 | _patterns.add(new ClassEntry(clazz, value)); |
37 | } |
38 | |
39 | /** |
40 | * Search if an object is an instance of one of the classes added to this |
41 | * ClassMatcher. For the first class in the list that is a superclass of the |
42 | * passed object, the matching value is returned. If there is no such class |
43 | * in the list, then <code>null</code> is returned. |
44 | * @param o the object to check against the list of classes |
45 | * @return the value associated with the first class in the list that is a |
46 | * superclass of <code>o</code> |
47 | */ |
48 | synchronized public Object get(Object o) |
49 | { |
50 | if (o == null) |
51 | { |
52 | return null; |
53 | } |
54 | |
55 | Class<?> clazz = o.getClass(); |
56 | for (ClassEntry entry: _patterns) |
57 | { |
58 | if (entry.getClazz().isAssignableFrom(clazz)) |
59 | { |
60 | return entry.getValue(); |
61 | } |
62 | } |
63 | return null; |
64 | } |
65 | |
66 | static private class ClassEntry |
67 | { |
68 | public ClassEntry(Class<?> clazz, Object value) |
69 | { |
70 | _clazz = clazz; |
71 | _value = value; |
72 | } |
73 | |
74 | public Class<?> getClazz() |
75 | { |
76 | return _clazz; |
77 | } |
78 | |
79 | public Object getValue() |
80 | { |
81 | return _value; |
82 | } |
83 | |
84 | private final Class _clazz; |
85 | private final Object _value; |
86 | } |
87 | |
88 | private final List<ClassEntry> _patterns = new ArrayList<ClassEntry>(); |
89 | } |