Java Tutorial/Reflection/Method

Материал из Java эксперт
Перейти к: навигация, поиск

Call a class method with 2 arguments

   <source lang="java">

import java.lang.reflect.Method; public class Main {

 public static void main(String[] args) throws Exception {
   Class c = Class.forName("MyClass");
   Method m = c.getDeclaredMethod("say", new Class[] { String.class, String.class });
   Object i = c.newInstance();
   Object r = m.invoke(i, new Object[] { "Hello","World" });
 }

} class MyClass {

 public void say(String s1, String s2) {
   System.out.println(s1 + " " + s2);
 }

}</source>





Call all possible exceptions during method invocation with reflection

   <source lang="java">

import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Invoke {

 public static void main(String[] args) {
   try {
     Class c = Class.forName(args[0]);
     Method m = c.getMethod(args[1]);
     Object ret = m.invoke(null);
     System.out.println("Invoked static method: " + args[1] + " of class: " + args[0]
         + " with no args\nResults: " + ret);
   } catch (ClassNotFoundException e) {
     System.out.println(e);
   } catch (NoSuchMethodException e2) {
     System.out.println(e2);
   } catch (IllegalAccessException e3) {
     System.out.println(e3);
   } catch (InvocationTargetException e) {
     System.out.println(e);
     System.out.println("Method threw an: " + e.getTargetException());
   }
 }

}</source>





Call a member function to get the value

   <source lang="java">

// $Id: ReflectionHelper.java 16271 2009-04-07 20:20:12Z hardy.ferentschik $ /*

  • JBoss, Home of Professional Open Source
  • Copyright 2008, Red Hat Middleware LLC, and individual contributors
  • by the @authors tag. See the copyright.txt in the distribution for a
  • full listing of individual contributors.
  • Licensed under the Apache License, Version 2.0 (the "License");
  • you may not use this file except in compliance with the License.
  • You may obtain a copy of the License at
  • http://www.apache.org/licenses/LICENSE-2.0
  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an "AS IS" BASIS,
  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  • See the License for the specific language governing permissions and
  • limitations under the License.
  • /

import java.beans.Introspector; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map;

/**

* Some reflection utility methods.
*
* @author Hardy Ferentschik
*/

public class ReflectionHelper {

 public static Object getValue(Member member, Object object) {
   Object value = null;
   if ( member instanceof Method ) {
     Method method = ( Method ) member;
     try {
       value = method.invoke( object );
     }
     catch ( IllegalAccessException e ) {
       throw new RuntimeException( "Unable to access " + method.getName(), e );
     }
     catch ( InvocationTargetException e ) {
       throw new RuntimeException( "Unable to access " + method.getName(), e );
     }
   }
   else if ( member instanceof Field ) {
     Field field = ( Field ) member;
     try {
       value = field.get( object );
     }
     catch ( IllegalAccessException e ) {
       throw new RuntimeException( "Unable to access " + field.getName(), e );
     }
   }
   return value;
 }

}</source>





Checks whether the specified class contains a method matching the specified name.

   <source lang="java">

// $Id: ReflectionHelper.java 16271 2009-04-07 20:20:12Z hardy.ferentschik $ /*

  • JBoss, Home of Professional Open Source
  • Copyright 2008, Red Hat Middleware LLC, and individual contributors
  • by the @authors tag. See the copyright.txt in the distribution for a
  • full listing of individual contributors.
  • Licensed under the Apache License, Version 2.0 (the "License");
  • you may not use this file except in compliance with the License.
  • You may obtain a copy of the License at
  • http://www.apache.org/licenses/LICENSE-2.0
  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an "AS IS" BASIS,
  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  • See the License for the specific language governing permissions and
  • limitations under the License.
  • /

import java.beans.Introspector; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; /**

* Some reflection utility methods.
*
* @author Hardy Ferentschik
*/

public class ReflectionHelper {

 /**
  * Checks whether the specified class contains a method matching the specified name.
  *
  * @param clazz The class to check.
  * @param methodName The method name.
  *
  * @return Returns true if the cass contains a property for the specified name, 
  *         false otherwise.
  */
 public static boolean containsMethod(Class<?> clazz, String methodName) {
   try {
     clazz.getMethod( "get" + methodName.substring( 0, 1 ).toUpperCase() + methodName.substring( 1 ) );
     return true;
   }
   catch ( NoSuchMethodException e ) {
     return false;
   }
 }

}</source>





Contains Same Method Signature

   <source lang="java">

// //$Id: IntrospectionUtil.java 1540 2007-01-19 12:24:10Z janb $ //Copyright 2006 Mort Bay Consulting Pty. Ltd. //------------------------------------------------------------------------ //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at //http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. // import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; public class IntrospectionUtil {

 public static boolean containsSameMethodSignature(Method method, Class c, boolean checkPackage) {
   if (checkPackage) {
     if (!c.getPackage().equals(method.getDeclaringClass().getPackage()))
       return false;
   }
   boolean samesig = false;
   Method[] methods = c.getDeclaredMethods();
   for (int i = 0; i < methods.length && !samesig; i++) {
     if (IntrospectionUtil.isSameSignature(method, methods[i]))
       samesig = true;
   }
   return samesig;
 }
 public static boolean containsSameFieldName(Field field, Class c, boolean checkPackage) {
   if (checkPackage) {
     if (!c.getPackage().equals(field.getDeclaringClass().getPackage()))
       return false;
   }
   boolean sameName = false;
   Field[] fields = c.getDeclaredFields();
   for (int i = 0; i < fields.length && !sameName; i++) {
     if (fields[i].getName().equals(field.getName()))
       sameName = true;
   }
   return sameName;
 }
 public static boolean isInheritable(Package pack, Member member) {
   if (pack == null)
     return false;
   if (member == null)
     return false;
   int modifiers = member.getModifiers();
   if (Modifier.isPublic(modifiers))
     return true;
   if (Modifier.isProtected(modifiers))
     return true;
   if (!Modifier.isPrivate(modifiers) && pack.equals(member.getDeclaringClass().getPackage()))
     return true;
   return false;
 }
 public static boolean checkParams(Class[] formalParams, Class[] actualParams, boolean strict) {
   if (formalParams == null && actualParams == null)
     return true;
   if (formalParams == null && actualParams != null)
     return false;
   if (formalParams != null && actualParams == null)
     return false;
   if (formalParams.length != actualParams.length)
     return false;
   if (formalParams.length == 0)
     return true;
   int j = 0;
   if (strict) {
     while (j < formalParams.length && formalParams[j].equals(actualParams[j]))
       j++;
   } else {
     while ((j < formalParams.length) && (formalParams[j].isAssignableFrom(actualParams[j]))) {
       j++;
     }
   }
   if (j != formalParams.length) {
     return false;
   }
   return true;
 }
 public static boolean isSameSignature(Method methodA, Method methodB) {
   if (methodA == null)
     return false;
   if (methodB == null)
     return false;
   List parameterTypesA = Arrays.asList(methodA.getParameterTypes());
   List parameterTypesB = Arrays.asList(methodB.getParameterTypes());
   if (methodA.getName().equals(methodB.getName()) && parameterTypesA.containsAll(parameterTypesB))
     return true;
   return false;
 }
 public static boolean isTypeCompatible(Class formalType, Class actualType, boolean strict) {
   if (formalType == null && actualType != null)
     return false;
   if (formalType != null && actualType == null)
     return false;
   if (formalType == null && actualType == null)
     return true;
   if (strict)
     return formalType.equals(actualType);
   else
     return formalType.isAssignableFrom(actualType);
 }
 protected static Method findInheritedMethod(Package pack, Class clazz, String methodName,
     Class[] args, boolean strictArgs) throws NoSuchMethodException {
   if (clazz == null)
     throw new NoSuchMethodException("No class");
   if (methodName == null)
     throw new NoSuchMethodException("No method name");
   Method method = null;
   Method[] methods = clazz.getDeclaredMethods();
   for (int i = 0; i < methods.length && method == null; i++) {
     if (methods[i].getName().equals(methodName) && isInheritable(pack, methods[i])
         && checkParams(methods[i].getParameterTypes(), args, strictArgs))
       method = methods[i];
   }
   if (method != null) {
     return method;
   } else
     return findInheritedMethod(clazz.getPackage(), clazz.getSuperclass(), methodName, args,
         strictArgs);
 }
 protected static Field findInheritedField(Package pack, Class clazz, String fieldName,
     Class fieldType, boolean strictType) throws NoSuchFieldException {
   if (clazz == null)
     throw new NoSuchFieldException("No class");
   if (fieldName == null)
     throw new NoSuchFieldException("No field name");
   try {
     Field field = clazz.getDeclaredField(fieldName);
     if (isInheritable(pack, field) && isTypeCompatible(fieldType, field.getType(), strictType))
       return field;
     else
       return findInheritedField(clazz.getPackage(), clazz.getSuperclass(), fieldName, fieldType,
           strictType);
   } catch (NoSuchFieldException e) {
     return findInheritedField(clazz.getPackage(), clazz.getSuperclass(), fieldName, fieldType,
         strictType);
   }
 }

}</source>





Demonstrates how to get simple method information

   <source lang="java">

/*

*     file: MethodInfoDemo.java
*  package: oreilly.hcj.reflection
*
* This software is granted under the terms of the Common Public License,
* CPL, which may be found at the following URL:
* http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm
*
* Copyright(c) 2003-2005 by the authors indicated in the @author tags.
* All Rights are Reserved by the various authors.
*
########## DO NOT EDIT ABOVE THIS LINE ########## */

import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /**

* Demonstrates how to get simple method information.
* 
* @author 
* @version $Revision: 1.3 $
*/

public class MethodInfoDemo {

 /**
  * __UNDOCUMENTED__
  * 
  * @param obj
  *          __UNDOCUMENTED__
  * 
  * @throws IllegalAccessException
  *           __UNDOCUMENTED__
  * @throws InvocationTargetException
  *           __UNDOCUMENTED__
  */
 public static void emptyStrings(final Object obj) throws IllegalAccessException,
     InvocationTargetException {
   final String PREFIX = "set"; //$NON-NLS-1$
   Method[] methods = obj.getClass().getMethods();
   for (int idx = 0; idx < methods.length; idx++) {
     if (methods[idx].getName().startsWith(PREFIX)) {
       if (methods[idx].getParameterTypes()[0] == String.class) {
         methods[idx].invoke(obj, new Object[] { new String() });
       }
     }
   }
 }
 /**
  * Demo method.
  * 
  * @param args
  *          Command line arguments.
  */
 public static void main(final String[] args) {
   String s = "";
   printMethodInfo(s);
   try {
     emptyStrings(s);
   } catch (final Exception ex) {
     ex.printStackTrace();
   }
 }
 /**
  * __UNDOCUMENTED__
  * 
  * @param obj
  *          __UNDOCUMENTED__
  */
 public static void printMethodInfo(final Object obj) {
   Class type = obj.getClass();
   final Method[] methods = type.getMethods();
   for (int idx = 0; idx < methods.length; idx++) {
     System.out.println(methods[idx]);
   }
 }

} /* ########## End of File ########## */</source>





Demonstrates how to get specific method information

   <source lang="java">

import java.lang.reflect.Method; /**

* Demonstrates how to get specific method information.
* 
* @author 
* @version $Revision: 1.3 $
*/

public class SpecificMethodInfoDemo {

 /**
  * Demo method.
  * 
  * @param args
  *          Command line arguments.
  * 
  * @throws RuntimeException
  *           If there is a reflection problem.
  */
 public static void main(final String[] args) {
   final Method byteValueMeth;
   final Method waitMeth;
   final Method waitDetailMeth;
   try {
     byteValueMeth = Number.class.getMethod("byteValue", null);
     waitMeth = Number.class.getMethod("wait", new Class[] {});
     waitDetailMeth = Number.class.getMethod("wait", new Class[] { long.class, int.class });
   } catch (final NoSuchMethodException ex) {
     throw new RuntimeException(ex);
   }
   System.out.println("byteValueMeth = " + byteValueMeth.toString());
   System.out.println("waitMeth = " + waitMeth.toString());
   System.out.println("waitDetailMeth = " + waitDetailMeth.toString());
 }

} /* ########## End of File ########## */</source>





Design your own class loader

   <source lang="java">

import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.Method; class MyClassLoader extends ClassLoader {

 public Class findClass(String name) {
   byte[] classData = null;
   try {
     FileInputStream f = new FileInputStream("C:\\" + name + ".class");
     int num = f.available();
     classData = new byte[num];
     f.read(classData);
   } catch (IOException e) {
     System.out.println(e);
   }
   Class x = defineClass(name, classData, 0, classData.length);
   return x;
 }

} public class MainClass {

 static public void main(String args[]) throws Exception {
   MyClassLoader x = new MyClassLoader();
   Class c = x.loadClass(args[0]);
   Class getArg1[] = { (new String[1]).getClass() };
   Method m = c.getMethod("main", getArg1);
   String[] my1 = { "arg1 passed", "arg2 passed" };
   Object myarg1[] = { my1 };
   m.invoke(null, myarg1);
 }

}</source>





Find method

   <source lang="java">

// //$Id: IntrospectionUtil.java 1540 2007-01-19 12:24:10Z janb $ //Copyright 2006 Mort Bay Consulting Pty. Ltd. //------------------------------------------------------------------------ //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at //http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. // import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; public class IntrospectionUtil {

 public static Method findMethod(Class clazz, String methodName, Class[] args,
     boolean checkInheritance, boolean strictArgs) throws NoSuchMethodException {
   if (clazz == null)
     throw new NoSuchMethodException("No class");
   if (methodName == null || methodName.trim().equals(""))
     throw new NoSuchMethodException("No method name");
   Method method = null;
   Method[] methods = clazz.getDeclaredMethods();
   for (int i = 0; i < methods.length && method == null; i++) {
     if (methods[i].getName().equals(methodName)
         && checkParams(methods[i].getParameterTypes(), (args == null ? new Class[] {} : args),
             strictArgs)) {
       method = methods[i];
     }
   }
   if (method != null) {
     return method;
   } else if (checkInheritance)
     return findInheritedMethod(clazz.getPackage(), clazz.getSuperclass(), methodName, args,
         strictArgs);
   else
     throw new NoSuchMethodException("No such method " + methodName + " on class "
         + clazz.getName());
 }
 public static Field findField(Class clazz, String targetName, Class targetType,
     boolean checkInheritance, boolean strictType) throws NoSuchFieldException {
   if (clazz == null)
     throw new NoSuchFieldException("No class");
   if (targetName == null)
     throw new NoSuchFieldException("No field name");
   try {
     Field field = clazz.getDeclaredField(targetName);
     if (strictType) {
       if (field.getType().equals(targetType))
         return field;
     } else {
       if (field.getType().isAssignableFrom(targetType))
         return field;
     }
     if (checkInheritance) {
       return findInheritedField(clazz.getPackage(), clazz.getSuperclass(), targetName,
           targetType, strictType);
     } else
       throw new NoSuchFieldException("No field with name " + targetName + " in class "
           + clazz.getName() + " of type " + targetType);
   } catch (NoSuchFieldException e) {
     return findInheritedField(clazz.getPackage(), clazz.getSuperclass(), targetName, targetType,
         strictType);
   }
 }
 public static boolean isInheritable(Package pack, Member member) {
   if (pack == null)
     return false;
   if (member == null)
     return false;
   int modifiers = member.getModifiers();
   if (Modifier.isPublic(modifiers))
     return true;
   if (Modifier.isProtected(modifiers))
     return true;
   if (!Modifier.isPrivate(modifiers) && pack.equals(member.getDeclaringClass().getPackage()))
     return true;
   return false;
 }
 public static boolean checkParams(Class[] formalParams, Class[] actualParams, boolean strict) {
   if (formalParams == null && actualParams == null)
     return true;
   if (formalParams == null && actualParams != null)
     return false;
   if (formalParams != null && actualParams == null)
     return false;
   if (formalParams.length != actualParams.length)
     return false;
   if (formalParams.length == 0)
     return true;
   int j = 0;
   if (strict) {
     while (j < formalParams.length && formalParams[j].equals(actualParams[j]))
       j++;
   } else {
     while ((j < formalParams.length) && (formalParams[j].isAssignableFrom(actualParams[j]))) {
       j++;
     }
   }
   if (j != formalParams.length) {
     return false;
   }
   return true;
 }
 public static boolean isSameSignature(Method methodA, Method methodB) {
   if (methodA == null)
     return false;
   if (methodB == null)
     return false;
   List parameterTypesA = Arrays.asList(methodA.getParameterTypes());
   List parameterTypesB = Arrays.asList(methodB.getParameterTypes());
   if (methodA.getName().equals(methodB.getName()) && parameterTypesA.containsAll(parameterTypesB))
     return true;
   return false;
 }
 public static boolean isTypeCompatible(Class formalType, Class actualType, boolean strict) {
   if (formalType == null && actualType != null)
     return false;
   if (formalType != null && actualType == null)
     return false;
   if (formalType == null && actualType == null)
     return true;
   if (strict)
     return formalType.equals(actualType);
   else
     return formalType.isAssignableFrom(actualType);
 }
 public static boolean containsSameMethodSignature(Method method, Class c, boolean checkPackage) {
   if (checkPackage) {
     if (!c.getPackage().equals(method.getDeclaringClass().getPackage()))
       return false;
   }
   boolean samesig = false;
   Method[] methods = c.getDeclaredMethods();
   for (int i = 0; i < methods.length && !samesig; i++) {
     if (IntrospectionUtil.isSameSignature(method, methods[i]))
       samesig = true;
   }
   return samesig;
 }
 public static boolean containsSameFieldName(Field field, Class c, boolean checkPackage) {
   if (checkPackage) {
     if (!c.getPackage().equals(field.getDeclaringClass().getPackage()))
       return false;
   }
   boolean sameName = false;
   Field[] fields = c.getDeclaredFields();
   for (int i = 0; i < fields.length && !sameName; i++) {
     if (fields[i].getName().equals(field.getName()))
       sameName = true;
   }
   return sameName;
 }
 protected static Method findInheritedMethod(Package pack, Class clazz, String methodName,
     Class[] args, boolean strictArgs) throws NoSuchMethodException {
   if (clazz == null)
     throw new NoSuchMethodException("No class");
   if (methodName == null)
     throw new NoSuchMethodException("No method name");
   Method method = null;
   Method[] methods = clazz.getDeclaredMethods();
   for (int i = 0; i < methods.length && method == null; i++) {
     if (methods[i].getName().equals(methodName) && isInheritable(pack, methods[i])
         && checkParams(methods[i].getParameterTypes(), args, strictArgs))
       method = methods[i];
   }
   if (method != null) {
     return method;
   } else
     return findInheritedMethod(clazz.getPackage(), clazz.getSuperclass(), methodName, args,
         strictArgs);
 }
 protected static Field findInheritedField(Package pack, Class clazz, String fieldName,
     Class fieldType, boolean strictType) throws NoSuchFieldException {
   if (clazz == null)
     throw new NoSuchFieldException("No class");
   if (fieldName == null)
     throw new NoSuchFieldException("No field name");
   try {
     Field field = clazz.getDeclaredField(fieldName);
     if (isInheritable(pack, field) && isTypeCompatible(fieldType, field.getType(), strictType))
       return field;
     else
       return findInheritedField(clazz.getPackage(), clazz.getSuperclass(), fieldName, fieldType,
           strictType);
   } catch (NoSuchFieldException e) {
     return findInheritedField(clazz.getPackage(), clazz.getSuperclass(), fieldName, fieldType,
         strictType);
   }
 }

}</source>





get Declared Method by name and parameter type

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class MethodTroubleReturns {

 private void drinkMe(int liters) {
   if (liters < 0)
     throw new IllegalArgumentException(
         "I can"t drink a negative amount of liquid");
 }
 public static void main(String... args) {
   try {
     MethodTroubleReturns mtr = new MethodTroubleReturns();
     Class<?> c = mtr.getClass();
     Method m = c.getDeclaredMethod("drinkMe", int.class);
     m.invoke(mtr, -1);
     // production code should handle these exceptions more gracefully
   } catch (InvocationTargetException x) {
     Throwable cause = x.getCause();
     System.err.format("drinkMe() failed: %s%n", cause.getMessage());
   } catch (Exception x) {
     x.printStackTrace();
   }
 }

}</source>





Get method from a class by name

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.lang.reflect.Method; public class ClassWarning {

 void m() {
   try {
     Class c = ClassWarning.class;
     Method m = c.getMethod("m"); // warning
     // production code should handle this exception more gracefully
   } catch (NoSuchMethodException x) {
     x.printStackTrace();
   }
 }

}</source>





Get method my parameters

   <source lang="java">

import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; @Retention(RetentionPolicy.RUNTIME) @interface MyAnno {

 String str();
 int val();

} class Meta {

 @MyAnno(str = "Two Parameters", val = 19)
 public static void myMeth(String str, int i) {
   Meta ob = new Meta();
   try {
     Class c = ob.getClass();
     Method m = c.getMethod("myMeth", String.class, int.class);
     MyAnno anno = m.getAnnotation(MyAnno.class);
     System.out.println(anno.str() + " " + anno.val());
   } catch (NoSuchMethodException exc) {
     System.out.println("Method Not Found.");
   }
 }
 public static void main(String args[]) {
   myMeth("test", 10);
 }

}</source>





Get super class and all its declared methods

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import static java.lang.System.out; import java.lang.reflect.Method; public class InheritedMethods {

 public static void main(String... args) {
   try {
     Class<?> c = Class.forName(args[0]);
     printMethods(c);
     Class parent = c.getSuperclass();
     while (parent != null) {
       printMethods(parent);
       parent = parent.getSuperclass();
     }
     // production code should handle this exception more gracefully
   } catch (ClassNotFoundException x) {
     x.printStackTrace();
   }
 }
 private static void printMethods(Class c) {
   out.format("Methods from %s%n", c);
   Method[] meths = c.getDeclaredMethods();
   if (meths.length != 0) {
     for (Method m : meths)
       out.format("  Method:  %s%n", m.toGenericString());
   } else {
     out.format("  -- no methods --%n");
   }
   out.format("%n");
 }

}</source>





Get the current method name

   <source lang="java">

public class Main{

   public static void main(String args[]) {
     System.out.println
        (new Exception().getStackTrace()[0].getMethodName());
   }

}</source>





Get the current method name With JDK1.5

   <source lang="java">

public class Main {

 public static void main(String args[]) {
   trace(Thread.currentThread().getStackTrace());
 }
 public static void trace(StackTraceElement e[]) {
   boolean doNext = false;
   for (StackTraceElement s : e) {
     if (doNext) {
       System.out.println(s.getMethodName());
       return;
     }
     doNext = s.getMethodName().equals("getStackTrace");
   }
 }

}</source>





Getting the Methods of a Class Object: By obtaining a list of all declared methods

   <source lang="java">

import java.lang.reflect.Method; public class Main {

 public static void main(String[] argv) throws Exception {
   Class cls = java.lang.String.class;
   
   Method[] methods = cls.getDeclaredMethods();
 }

}</source>





Getting the Methods of a Class Object: By obtaining a list of all public methods, both declared and inherited.

   <source lang="java">

import java.lang.reflect.Method; public class Main {

 public static void main(String[] argv) throws Exception {
   Class cls = java.lang.String.class;
   Method[] methods = cls.getMethods();
   for (int i = 0; i < methods.length; i++) {
     Class returnType = methods[i].getReturnType();
     Class[] paramTypes = methods[i].getParameterTypes();
     System.out.println(methods[i]);
   }
 }

}</source>





Getting the Methods of a Class Object: By obtaining a particular Method object.

   <source lang="java">

import java.lang.reflect.Method; public class Main {

 public static void main(String[] argv) throws Exception {
   Class cls = java.lang.String.class;
   Method method = cls.getMethod("substring", new Class[] { int.class });
   System.out.println(method);
 }

}</source>





Invoke a method with parameter

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; public class InvokeMain {

 public static void main(String... args) {
   try {
     Class<?> c = Class.forName(args[0]);
     Class[] argTypes = new Class[] { String[].class };
     Method main = c.getDeclaredMethod("main", argTypes);
     String[] mainArgs = Arrays.copyOfRange(args, 1, args.length);
     System.out.format("invoking %s.main()%n", c.getName());
     main.invoke(null, (Object) mainArgs);
     // production code should handle these exceptions more gracefully
   } catch (ClassNotFoundException x) {
     x.printStackTrace();
   } catch (NoSuchMethodException x) {
     x.printStackTrace();
   } catch (IllegalAccessException x) {
     x.printStackTrace();
   } catch (InvocationTargetException x) {
     x.printStackTrace();
   }
 }

}</source>





Invoke methods of an object using reflection

   <source lang="java">

import java.lang.reflect.Method; public class Main {

 public static void main(String[] args) throws Exception {
   Class computerClass = MyClass.class;
   Method[] methods = computerClass.getDeclaredMethods();
   MyClass computer = new MyClass();
   for (Method method : methods) {
     Object result = method.invoke(computer, new Object[0]);
     System.out.println(method.getName() + ": " + result);
   }
 }

} class MyClass {

 private String type = "type";
 public String getType() {
   return type;
 }

} //getType: type</source>





Invoke method with wrong parameters

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.lang.reflect.Method; public class MethodTroubleToo {

 public void ping() {
   System.out.format("PONG!%n");
 }
 public static void main(String... args) {
   try {
     MethodTroubleToo mtt = new MethodTroubleToo();
     Method m = MethodTroubleToo.class.getMethod("ping");
     switch (Integer.parseInt(args[0])) {
     case 0:
       m.invoke(mtt); // works
       break;
     case 1:
       m.invoke(mtt, null); // works (expect compiler warning)
       break;
     case 2:
       Object arg2 = null;
       m.invoke(mtt, arg2); // IllegalArgumentException
       break;
     case 3:
       m.invoke(mtt, new Object[0]); // works
       break;
     case 4:
       Object arg4 = new Object[0];
       m.invoke(mtt, arg4); // IllegalArgumentException
       break;
     default:
       System.out.format("Test not found%n");
     }
     // production code should handle these exceptions more gracefully
   } catch (Exception x) {
     x.printStackTrace();
   }
 }

}</source>





List methods of a class using Reflection

   <source lang="java">

import java.lang.reflect.Method; public class Main {

 public static void main(String[] args) {
   Class aClass = String.class;
   // Get the methods
   Method[] methods = aClass.getDeclaredMethods();
   // Loop through the methods and print out their names
   for (Method method : methods) {
     System.out.println(method.getName());
   }
 }

} /* hashCode compareTo compareTo indexOf indexOf indexOf indexOf indexOf equals toString charAt checkBounds codePointAt codePointBefore codePointCount compareToIgnoreCase concat contains contentEquals contentEquals copyValueOf copyValueOf endsWith equalsIgnoreCase format format getBytes getBytes getBytes getBytes getChars getChars intern isEmpty lastIndexOf lastIndexOf lastIndexOf lastIndexOf lastIndexOf length matches offsetByCodePoints regionMatches regionMatches replace replace replaceAll replaceFirst split split startsWith startsWith subSequence substring substring toCharArray toLowerCase toLowerCase toUpperCase toUpperCase trim valueOf valueOf valueOf valueOf valueOf valueOf valueOf valueOf valueOf

  • /</source>





Method Inspector

   <source lang="java">

import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class MethodInspector {

 public static void main(String[] arguments) {
   Class inspect;
   try {
     if (arguments.length > 0)
       inspect = Class.forName(arguments[0]);
     else
       inspect = Class.forName("MethodInspector");
     Method[] methods = inspect.getDeclaredMethods();
     for (int i = 0; i < methods.length; i++) {
       Method methVal = methods[i];
       Class returnVal = methVal.getReturnType();
       int mods = methVal.getModifiers();
       String modVal = Modifier.toString(mods);
       Class[] paramVal = methVal.getParameterTypes();
       StringBuffer params = new StringBuffer();
       for (int j = 0; j < paramVal.length; j++) {
         if (j > 0)
           params.append(", ");
         params.append(paramVal[j].getName());
       }
       System.out.println("Method: " + methVal.getName() + "()");
       System.out.println("Modifiers: " + modVal);
       System.out.println("Return Type: " + returnVal.getName());
       System.out.println("Parameters: " + params + "\n");
     }
   } catch (ClassNotFoundException c) {
     System.out.println(c.toString());
   }
 }

}</source>





Prints out the declared methods on java.lang.Number

   <source lang="java">

/*

*     file: DeclaredMethodInfoDemo.java
*  package: oreilly.hcj.reflection
*
* This software is granted under the terms of the Common Public License,
* CPL, which may be found at the following URL:
* http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm
*
* Copyright(c) 2003-2005 by the authors indicated in the @author tags.
* All Rights are Reserved by the various authors.
*
                    1. DO NOT EDIT ABOVE THIS LINE ########## */

//package oreilly.hcj.reflection; import java.lang.reflect.Method; /**

* Prints out the declared methods on java.lang.Number.
*
* @author 
* @version $Revision: 1.3 $
*/

public class DeclaredMethodInfoDemo {

 /** 
  * Demon method.
  *
  * @param args Command line arguments.
  */
 public static void main(final String[] args) {
   final Method[] methods = Number.class.getDeclaredMethods();
   for (int idx = 0; idx < methods.length; idx++) {
     System.out.println(methods[idx]);
   }
 }

} /* ########## End of File ########## */</source>





Prints out the declared methods on java.lang.Object

   <source lang="java">

/*

*     file: ObjectDeclaredMethods.java
*  package: oreilly.hcj.reflection
*
* This software is granted under the terms of the Common Public License,
* CPL, which may be found at the following URL:
* http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm
*
* Copyright(c) 2003-2005 by the authors indicated in the @author tags.
* All Rights are Reserved by the various authors.
*
                    1. DO NOT EDIT ABOVE THIS LINE ########## */

import java.lang.reflect.Method; /**

* Prints out the declared methods on java.lang.Object.
*
* @author 
* @version $Revision: 1.3 $
*/

public class ObjectDeclaredMethods {

 /** 
  * Demon method.
  *
  * @param args Command line arguments.
  */
 public static void main(final String[] args) {
   final Method[] methods = Object.class.getDeclaredMethods();
   for (int idx = 0; idx < methods.length; idx++) {
     System.out.println(methods[idx]);
   }
 }

} /* ########## End of File ########## */</source>





Returns method with the specified name

   <source lang="java">

// $Id: ReflectionHelper.java 16271 2009-04-07 20:20:12Z hardy.ferentschik $ /*

  • JBoss, Home of Professional Open Source
  • Copyright 2008, Red Hat Middleware LLC, and individual contributors
  • by the @authors tag. See the copyright.txt in the distribution for a
  • full listing of individual contributors.
  • Licensed under the Apache License, Version 2.0 (the "License");
  • you may not use this file except in compliance with the License.
  • You may obtain a copy of the License at
  • http://www.apache.org/licenses/LICENSE-2.0
  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an "AS IS" BASIS,
  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  • See the License for the specific language governing permissions and
  • limitations under the License.
  • /

import java.beans.Introspector; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; /**

* Some reflection utility methods.
*
* @author Hardy Ferentschik
*/

public class ReflectionHelper {

 /**
  * Returns the method with the specified name or null if it does not exist.
  *
  * @param clazz The class to check.
  * @param methodName The method name.
  *
  * @return Returns the method with the specified name or null if it does not exist.
  */
 public static Method getMethod(Class<?> clazz, String methodName) {
   try {
     return clazz.getMethod( "get" + methodName.substring( 0, 1 ).toUpperCase() + methodName.substring( 1 ) );
   }
   catch ( NoSuchMethodException e ) {
     return null;
   }
 }

}</source>





Show public methods.

   <source lang="java">

import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class ReflectionDemo2 {

 public static void main(String args[]) {
   try {
     A a = new A();
     Class c = a.getClass();
     System.out.println("Public Methods:");
     Method methods[] = c.getDeclaredMethods();
     for (int i = 0; i < methods.length; i++) {
       int modifiers = methods[i].getModifiers();
       if (Modifier.isPublic(modifiers)) {
         System.out.println(" " + methods[i].getName());
       }
     }
   } catch (Exception e) {
     System.out.println("Exception: " + e);
   }
 }

} class A {

 public void a1() {
 }
 public void a2() {
 }
 protected void a3() {
 }
 private void a4() {
 }

}</source>





Sorts methods according to their name, number of parameters, and parameter types.

   <source lang="java">

/**

* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import java.lang.reflect.Method; import java.util.ruparator; /**

* Sorts methods according to their name, number of parameters, and parameter
* types.
*/

public class MethodComparator implements Comparator<Method> {

   public int compare(Method m1, Method m2) {
       int val = m1.getName().rupareTo(m2.getName());
       if (val == 0) {
           val = m1.getParameterTypes().length - m2.getParameterTypes().length;
           if (val == 0) {
               Class[] types1 = m1.getParameterTypes();
               Class[] types2 = m2.getParameterTypes();
               for (int i = 0; i < types1.length; i++) {
                   val = types1[i].getName().rupareTo(types2[i].getName());
                   if (val != 0) {
                       break;
                   }
               }
           }
       }
       return val;
   }

}</source>