001/* 002 * Copyright The Apache Software Foundation 003 * 004 * Licensed to the Apache Software Foundation (ASF) under one 005 * or more contributor license agreements. See the NOTICE file 006 * distributed with this work for additional information 007 * regarding copyright ownership. The ASF licenses this file 008 * to you under the Apache License, Version 2.0 (the 009 * "License"); you may not use this file except in compliance 010 * with the License. You may obtain a copy of the License at 011 * 012 * http://www.apache.org/licenses/LICENSE-2.0 013 * 014 * Unless required by applicable law or agreed to in writing, software 015 * distributed under the License is distributed on an "AS IS" BASIS, 016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 017 * See the License for the specific language governing permissions and 018 * limitations under the License. 019 */ 020package org.apache.hadoop.hbase.util; 021 022import java.lang.reflect.InvocationTargetException; 023import java.lang.reflect.Method; 024import java.lang.reflect.UndeclaredThrowableException; 025 026import org.apache.hadoop.hbase.log.HBaseMarkers; 027import org.apache.yetus.audience.InterfaceAudience; 028import org.slf4j.Logger; 029import org.slf4j.LoggerFactory; 030 031@InterfaceAudience.Private 032public final class Methods { 033 private static final Logger LOG = LoggerFactory.getLogger(Methods.class); 034 035 private Methods() { 036 } 037 038 public static <T> Object call(Class<T> clazz, T instance, String methodName, 039 Class[] types, Object[] args) throws Exception { 040 try { 041 Method m = clazz.getMethod(methodName, types); 042 return m.invoke(instance, args); 043 } catch (IllegalArgumentException arge) { 044 LOG.error(HBaseMarkers.FATAL, "Constructed invalid call. class="+clazz.getName()+ 045 " method=" + methodName + " types=" + Classes.stringify(types), arge); 046 throw arge; 047 } catch (NoSuchMethodException nsme) { 048 throw new IllegalArgumentException( 049 "Can't find method "+methodName+" in "+clazz.getName()+"!", nsme); 050 } catch (InvocationTargetException ite) { 051 // unwrap the underlying exception and rethrow 052 if (ite.getTargetException() != null) { 053 if (ite.getTargetException() instanceof Exception) { 054 throw (Exception)ite.getTargetException(); 055 } else if (ite.getTargetException() instanceof Error) { 056 throw (Error)ite.getTargetException(); 057 } 058 } 059 throw new UndeclaredThrowableException(ite, 060 "Unknown exception invoking "+clazz.getName()+"."+methodName+"()"); 061 } catch (IllegalAccessException iae) { 062 throw new IllegalArgumentException( 063 "Denied access calling "+clazz.getName()+"."+methodName+"()", iae); 064 } catch (SecurityException se) { 065 LOG.error(HBaseMarkers.FATAL, "SecurityException calling method. class="+ 066 clazz.getName()+" method=" + methodName + " types=" + 067 Classes.stringify(types), se); 068 throw se; 069 } 070 } 071}