01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17: package org.apache.servicemix.cxfse.support;
18:
19: import java.lang.annotation.Annotation;
20: import java.lang.reflect.Field;
21: import java.lang.reflect.InvocationTargetException;
22: import java.lang.reflect.Method;
23: import java.lang.reflect.Modifier;
24:
25: public class ReflectionUtils extends
26: org.springframework.util.ReflectionUtils {
27:
28: public static <T extends Annotation> void callLifecycleMethod(
29: final Object bean, final Class<T> annotation) {
30: ReflectionUtils.doWithMethods(bean.getClass(),
31: new ReflectionUtils.MethodCallback() {
32: public void doWith(Method method)
33: throws IllegalArgumentException,
34: IllegalAccessException {
35: if (method.getAnnotation(annotation) != null) {
36: try {
37: method.invoke(bean, (Object[]) null);
38: } catch (IllegalArgumentException ex) {
39: throw new IllegalStateException(
40: "Failure to invoke " + method
41: + " on "
42: + bean.getClass()
43: + ": args=[]", ex);
44: } catch (IllegalAccessException ex) {
45: throw new UnsupportedOperationException(
46: ex.toString());
47: } catch (InvocationTargetException ex) {
48: throw new UnsupportedOperationException(
49: "PostConstruct method on bean threw exception",
50: ex.getTargetException());
51: }
52: }
53: }
54: });
55: }
56:
57: public static void setField(Field f, Object instance, Object value) {
58: try {
59: boolean oldAccessible = f.isAccessible();
60: boolean shouldSetAccessible = !Modifier.isPublic(f
61: .getModifiers())
62: && !oldAccessible;
63: if (shouldSetAccessible) {
64: f.setAccessible(true);
65: }
66: f.set(instance, value);
67: if (shouldSetAccessible) {
68: f.setAccessible(oldAccessible);
69: }
70: } catch (IllegalArgumentException ex) {
71: throw new UnsupportedOperationException(
72: "Cannot inject value of class '" + value.getClass()
73: + "' into " + f);
74: } catch (IllegalAccessException ex) {
75: ReflectionUtils.handleReflectionException(ex);
76: }
77: }
78:
79: }
|