View Javadoc

1   /*
2    * Copyright 2004 Ronald Blaschke.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.rblasch.convert.converters;
17  
18  import org.rblasch.convert.MetaConverter;
19  import org.rblasch.convert.type.Type;
20  import org.rblasch.convert.type.Types;
21  
22  import java.lang.reflect.Method;
23  import java.util.Arrays;
24  import java.util.HashSet;
25  import java.util.Iterator;
26  import java.util.Set;
27  
28  /***
29   * @author Ronald Blaschke
30   */
31  public class ObjectToMetaConvertersConverter extends AbstractConverter {
32      private final int weight;
33  
34      public ObjectToMetaConvertersConverter(final int weight) {
35          this.weight = weight;
36      }
37  
38      public Type getSourceType() {
39          return Types.findTypeByClass(Object.class);
40      }
41  
42      public Type getDestinationType() {
43          return Types.findPTypeByClass(Set.class, MetaConverter.class);
44      }
45  
46      public int getWeight() {
47          return 100;
48      }
49  
50      public Object convert(final Object obj) throws Exception {
51          final Set/*<MetaConverter>*/ converters = new HashSet();
52  
53          for (final Iterator i = Arrays.asList(obj.getClass().getMethods()).iterator(); i.hasNext();) {
54              final Method m = (Method) i.next();
55              if (m.getName().startsWith("convert")
56                      && m.getParameterTypes().length == 1
57                      && !m.getReturnType().equals(Void.TYPE)) {
58                  converters.add(new AbstractClassConverter() {
59                      public Class getSourceClass() {
60                          return m.getParameterTypes()[0];
61                      }
62  
63                      public Class getDestinationClass() {
64                          return m.getReturnType();
65                      }
66  
67                      public int getWeight() {
68                          return weight;
69                      }
70  
71                      public Object convert(final Object arg) throws Exception {
72                          return m.invoke(obj, new Object[]{arg});
73                      }
74                  });
75              }
76          }
77  
78          return converters;
79      }
80  }