ReflectionUtils.java revision 442aee6bc1abfb143dcfa1ba60d696e576d066c4
1/* 2 * Copyright (C) 2015 The Android Open Source Project 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 17package com.android.layoutlib.bridge.util; 18 19import android.annotation.NonNull; 20import android.annotation.Nullable; 21 22import java.lang.reflect.InvocationTargetException; 23import java.lang.reflect.Method; 24 25/** 26 * Utility to convert checked Reflection exceptions to unchecked exceptions. 27 */ 28public class ReflectionUtils { 29 30 @Nullable 31 public static Method getMethod(@NonNull Class<?> clazz, @NonNull String name, 32 @Nullable Class<?>... params) throws ReflectionException { 33 try { 34 return clazz.getMethod(name, params); 35 } catch (NoSuchMethodException e) { 36 throw new ReflectionException(e); 37 } 38 } 39 40 @Nullable 41 public static Object invoke(@NonNull Method method, @Nullable Object object, 42 @Nullable Object... args) throws ReflectionException { 43 Exception ex; 44 try { 45 return method.invoke(object, args); 46 } catch (IllegalAccessException e) { 47 ex = e; 48 } catch (InvocationTargetException e) { 49 ex = e; 50 } 51 throw new ReflectionException(ex); 52 } 53 54 /** 55 * Wraps all reflection related exceptions. Created since ReflectiveOperationException was 56 * introduced in 1.7 and we are still on 1.6 57 */ 58 public static class ReflectionException extends Exception { 59 public ReflectionException() { 60 super(); 61 } 62 63 public ReflectionException(String message) { 64 super(message); 65 } 66 67 public ReflectionException(String message, Throwable cause) { 68 super(message, cause); 69 } 70 71 public ReflectionException(Throwable cause) { 72 super(cause); 73 } 74 } 75} 76