Java by API/java.lang.reflect/Method
Содержание
- 1 Method: getAnnotation(Class < MyAnno > annotationClass)
- 2 Method: getExceptionTypes()
- 3 Method: getModifiers()
- 4 Method: getName()
- 5 Method: getParameterTypes()
- 6 Method: getReturnType()
- 7 Method: invoke(Object obj, Object... args)
- 8 Method: setAccessible(boolean flag)
- 9 Method: toGenericString()
- 10 Method: toString()
Method: getAnnotation(Class < MyAnno > annotationClass)
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str();
int val();
}
public class MainClass {
@MyAnno(str = "Annotation Example", val = 100)
public static void myMeth() {
MainClass ob = new MainClass();
try {
Class c = ob.getClass();
Method m = c.getMethod("myMeth");
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();
}
}
Method: getExceptionTypes()
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Main{
public static void main(String[] args) throws ClassNotFoundException {
Class c = Class.forName(args[0]);
print_class(c);
}
public static void print_class(Class c) {
if (c.isInterface()) {
System.out.print(Modifier.toString(c.getModifiers()) + " " + typename(c));
} else if (c.getSuperclass() != null) {
System.out.print(Modifier.toString(c.getModifiers()) + " class " + typename(c) + " extends "
+ typename(c.getSuperclass()));
} else {
System.out.print(Modifier.toString(c.getModifiers()) + " class " + typename(c));
}
Class[] interfaces = c.getInterfaces();
if ((interfaces != null) && (interfaces.length > 0)) {
if (c.isInterface())
System.out.print(" extends ");
else
System.out.print(" implements ");
for (int i = 0; i < interfaces.length; i++) {
if (i > 0)
System.out.print(", ");
System.out.print(typename(interfaces[i]));
}
}
System.out.println(" {");
Constructor[] constructors = c.getDeclaredConstructors();
for (int i = 0; i < constructors.length; i++)
print_method_or_constructor(constructors[i]);
Field[] fields = c.getDeclaredFields();
for (int i = 0; i < fields.length; i++){
print_field(fields[i]);
}
Method[] methods = c.getDeclaredMethods();
for (int i = 0; i < methods.length; i++)
print_method_or_constructor(methods[i]);
System.out.println("}");
}
public static String typename(Class t) {
String brackets = "";
while (t.isArray()) {
brackets += "[]";
t = t.getComponentType();
}
String name = t.getName();
int pos = name.lastIndexOf(".");
if (pos != -1)
name = name.substring(pos + 1);
return name + brackets;
}
public static String modifiers(int m) {
if (m == 0)
return "";
else
return Modifier.toString(m) + " ";
}
public static void print_field(Field f) {
System.out.println(" " + modifiers(f.getModifiers()) + typename(f.getType()) + " "
+ f.getName() + ";");
}
public static void print_method_or_constructor(Member member) {
Class returntype = null, parameters[], exceptions[];
if (member instanceof Method) {
Method m = (Method) member;
returntype = m.getReturnType();
parameters = m.getParameterTypes();
exceptions = m.getExceptionTypes();
System.out.print(" " + modifiers(member.getModifiers()) + typename(returntype) + " "
+ member.getName() + "(");
} else {
Constructor c = (Constructor) member;
parameters = c.getParameterTypes();
exceptions = c.getExceptionTypes();
System.out.print(" " + modifiers(member.getModifiers()) + typename(c.getDeclaringClass())
+ "(");
}
for (int i = 0; i < parameters.length; i++) {
if (i > 0)
System.out.print(", ");
System.out.print(typename(parameters[i]));
}
System.out.print(")");
if (exceptions.length > 0)
System.out.print(" throws ");
for (int i = 0; i < exceptions.length; i++) {
if (i > 0)
System.out.print(", ");
System.out.print(typename(exceptions[i]));
}
System.out.println(";");
}
}
Method: getModifiers()
/*
* Output:
Public Methods:
a1
a2
* */
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class MainClass {
public static void main(String args[]) {
try {
MyClass a = new MyClass();
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 MyClass {
public void a1() {
}
public void a2() {
}
protected void a3() {
}
private void a4() {
}
}
Method: getName()
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Main {
public static void main(String[] args) {
String name = "java.util.Date";
try {
Class cl = Class.forName(name);
System.out.println("class " + name);
System.out.println("Its methods:");
printMethods(cl);
System.out.println();
} catch (ClassNotFoundException e) {
System.out.println("Class not found.");
}
}
public static void printMethods(Class cl) {
Method[] methods = cl.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method m = methods[i];
Class retType = m.getReturnType();
Class[] paramTypes = m.getParameterTypes();
String name = m.getName();
System.out.print(Modifier.toString(m.getModifiers()));
System.out.print(" " + retType.getName() + " " + name + "(");
for (int j = 0; j < paramTypes.length; j++) {
if (j > 0)
System.out.print(", ");
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}
}
Method: getParameterTypes()
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Main{
public static void main(String[] args) throws ClassNotFoundException {
Class c = Class.forName(args[0]);
print_class(c);
}
public static void print_class(Class c) {
if (c.isInterface()) {
System.out.print(Modifier.toString(c.getModifiers()) + " " + typename(c));
} else if (c.getSuperclass() != null) {
System.out.print(Modifier.toString(c.getModifiers()) + " class " + typename(c) + " extends "
+ typename(c.getSuperclass()));
} else {
System.out.print(Modifier.toString(c.getModifiers()) + " class " + typename(c));
}
Class[] interfaces = c.getInterfaces();
if ((interfaces != null) && (interfaces.length > 0)) {
if (c.isInterface())
System.out.print(" extends ");
else
System.out.print(" implements ");
for (int i = 0; i < interfaces.length; i++) {
if (i > 0)
System.out.print(", ");
System.out.print(typename(interfaces[i]));
}
}
System.out.println(" {");
Constructor[] constructors = c.getDeclaredConstructors();
for (int i = 0; i < constructors.length; i++)
print_method_or_constructor(constructors[i]);
Field[] fields = c.getDeclaredFields();
for (int i = 0; i < fields.length; i++){
print_field(fields[i]);
}
Method[] methods = c.getDeclaredMethods();
for (int i = 0; i < methods.length; i++)
print_method_or_constructor(methods[i]);
System.out.println("}");
}
public static String typename(Class t) {
String brackets = "";
while (t.isArray()) {
brackets += "[]";
t = t.getComponentType();
}
String name = t.getName();
int pos = name.lastIndexOf(".");
if (pos != -1)
name = name.substring(pos + 1);
return name + brackets;
}
public static String modifiers(int m) {
if (m == 0)
return "";
else
return Modifier.toString(m) + " ";
}
public static void print_field(Field f) {
System.out.println(" " + modifiers(f.getModifiers()) + typename(f.getType()) + " "
+ f.getName() + ";");
}
public static void print_method_or_constructor(Member member) {
Class returntype = null, parameters[], exceptions[];
if (member instanceof Method) {
Method m = (Method) member;
returntype = m.getReturnType();
parameters = m.getParameterTypes();
exceptions = m.getExceptionTypes();
System.out.print(" " + modifiers(member.getModifiers()) + typename(returntype) + " "
+ member.getName() + "(");
} else {
Constructor c = (Constructor) member;
parameters = c.getParameterTypes();
exceptions = c.getExceptionTypes();
System.out.print(" " + modifiers(member.getModifiers()) + typename(c.getDeclaringClass())
+ "(");
}
for (int i = 0; i < parameters.length; i++) {
if (i > 0)
System.out.print(", ");
System.out.print(typename(parameters[i]));
}
System.out.print(")");
if (exceptions.length > 0)
System.out.print(" throws ");
for (int i = 0; i < exceptions.length; i++) {
if (i > 0)
System.out.print(", ");
System.out.print(typename(exceptions[i]));
}
System.out.println(";");
}
}
Method: getReturnType()
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Main{
public static void main(String[] args) throws ClassNotFoundException {
Class c = Class.forName(args[0]);
print_class(c);
}
public static void print_class(Class c) {
if (c.isInterface()) {
System.out.print(Modifier.toString(c.getModifiers()) + " " + typename(c));
} else if (c.getSuperclass() != null) {
System.out.print(Modifier.toString(c.getModifiers()) + " class " + typename(c) + " extends "
+ typename(c.getSuperclass()));
} else {
System.out.print(Modifier.toString(c.getModifiers()) + " class " + typename(c));
}
Class[] interfaces = c.getInterfaces();
if ((interfaces != null) && (interfaces.length > 0)) {
if (c.isInterface())
System.out.print(" extends ");
else
System.out.print(" implements ");
for (int i = 0; i < interfaces.length; i++) {
if (i > 0)
System.out.print(", ");
System.out.print(typename(interfaces[i]));
}
}
System.out.println(" {");
Constructor[] constructors = c.getDeclaredConstructors();
for (int i = 0; i < constructors.length; i++)
print_method_or_constructor(constructors[i]);
Field[] fields = c.getDeclaredFields();
for (int i = 0; i < fields.length; i++){
print_field(fields[i]);
}
Method[] methods = c.getDeclaredMethods();
for (int i = 0; i < methods.length; i++)
print_method_or_constructor(methods[i]);
System.out.println("}");
}
public static String typename(Class t) {
String brackets = "";
while (t.isArray()) {
brackets += "[]";
t = t.getComponentType();
}
String name = t.getName();
int pos = name.lastIndexOf(".");
if (pos != -1)
name = name.substring(pos + 1);
return name + brackets;
}
public static String modifiers(int m) {
if (m == 0)
return "";
else
return Modifier.toString(m) + " ";
}
public static void print_field(Field f) {
System.out.println(" " + modifiers(f.getModifiers()) + typename(f.getType()) + " "
+ f.getName() + ";");
}
public static void print_method_or_constructor(Member member) {
Class returntype = null, parameters[], exceptions[];
if (member instanceof Method) {
Method m = (Method) member;
returntype = m.getReturnType();
parameters = m.getParameterTypes();
exceptions = m.getExceptionTypes();
System.out.print(" " + modifiers(member.getModifiers()) + typename(returntype) + " "
+ member.getName() + "(");
} else {
Constructor c = (Constructor) member;
parameters = c.getParameterTypes();
exceptions = c.getExceptionTypes();
System.out.print(" " + modifiers(member.getModifiers()) + typename(c.getDeclaringClass())
+ "(");
}
for (int i = 0; i < parameters.length; i++) {
if (i > 0)
System.out.print(", ");
System.out.print(typename(parameters[i]));
}
System.out.print(")");
if (exceptions.length > 0)
System.out.print(" throws ");
for (int i = 0; i < exceptions.length; i++) {
if (i > 0)
System.out.print(", ");
System.out.print(typename(exceptions[i]));
}
System.out.println(";");
}
}
Method: invoke(Object obj, Object... args)
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MainClass {
public static void main(String args[]) throws Exception {
try {
Class c = Class.forName("java.text.NumberFormat");
Method m = c.getMethod("getInstance");
Object ret = m.invoke(null);
System.out.println("Results: " + ret);
} catch (ClassNotFoundException e) {
System.out.println("Class.forName( ) can"t find the class");
} catch (NoSuchMethodException e2) {
System.out.println("method doesn"t exist");
} catch (IllegalAccessException e3) {
System.out.println("no permission to invoke that method");
} catch (InvocationTargetException e) {
System.out.println("an exception ocurred while invoking that method");
System.out.println("Method threw an: " + e.getTargetException());
}
}
}
Method: setAccessible(boolean flag)
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
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.getMethods()[0];
Field field = cls.getFields()[0];
Constructor constructor = cls.getConstructors()[0];
field.setAccessible(true);
constructor.setAccessible(true);
method.setAccessible(true);
}
}
Method: toGenericString()
/*
* 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;
import java.lang.reflect.Type;
public class Main {
private static final String fmt = "%24s: %s%n";
// for the morbidly curious
<E extends RuntimeException> void genericThrow() throws E {
}
public static void main(String... args) throws Exception {
Class<?> c = Class.forName(args[0]);
Method[] allMethods = c.getDeclaredMethods();
for (Method m : allMethods) {
if (!m.getName().equals(args[1])) {
continue;
}
out.format("%s%n", m.toGenericString());
Class<?>[] xType = m.getExceptionTypes();
Type[] gxType = m.getGenericExceptionTypes();
for (int i = 0; i < xType.length; i++) {
out.format(fmt, "ExceptionType", xType[i]);
out.format(fmt, "GenericExceptionType", gxType[i]);
}
}
}
}
Method: toString()
import java.lang.reflect.Method;
/**
* Demonstrates how to get specific method information.
*
* @author
* @version $Revision: 1.3 $
*/
public class Main {
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());
}
}