Java : Method (reflection) with Examples
Method (Java SE 18 & JDK 18) API Examples.
You will find code examples on most Method methods.
Summary
A Method provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method).
public class AccessTest {
private int sum(int a, int b) {
return a + b;
}
}
final var cls = AccessTest.class;
final var obj = new AccessTest();
final var method = cls.getDeclaredMethod("sum", int.class, int.class);
System.out.println(method); // private int AccessTest.sum(int,int)
System.out.println(method.canAccess(obj)); // false
//method.invoke(obj, 20, 30); // IllegalAccessException
System.out.println(method.trySetAccessible()); // true
System.out.println(method.canAccess(obj)); // true
final var ret = method.invoke(obj, 20, 30);
System.out.println(ret); // 50
Fields declared in Member
Methods
boolean equals (Object obj)
Compares this Method against the specified object.
public class Foo {
public void aaa() {
}
public void bbb() {
}
}
final var foo1 = new Foo();
final var foo2 = new Foo();
final var method1 = foo1.getClass().getDeclaredMethod("aaa");
final var method2 = foo2.getClass().getDeclaredMethod("aaa");
System.out.println(method1.equals(method2)); // true
final var method3 = foo1.getClass().getDeclaredMethod("bbb");
System.out.println(method3.equals(method1)); // false
AnnotatedType getAnnotatedReturnType ()
Returns an AnnotatedType object that represents the use of a type to specify the return type of the method/constructor represented by this Executable.
public class Foo {
public int aaa() {
return 123;
}
public String bbb() {
return "abc";
}
}
final var cls = Foo.class;
final var method = cls.getDeclaredMethod("aaa");
System.out.println(method); // public int Foo.aaa()
final var type = method.getAnnotatedReturnType();
System.out.println(type); // int
final var cls = Foo.class;
final var method = cls.getDeclaredMethod("bbb");
System.out.println(method); // public java.lang.String Foo.bbb()
final var type = method.getAnnotatedReturnType();
System.out.println(type); // java.lang.String
<T extends Annotation> T getAnnotation (Class<T> annotationClass)
Returns this element's annotation for the specified type if such an annotation is present, else null.
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Foo {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Bar {
}
public class A {
@Foo
public void aaa() {
}
@Bar
public void bbb() {
}
}
final var method = A.class.getDeclaredMethod("aaa");
final var ret1 = method.getAnnotation(Foo.class);
System.out.println(ret1); // @Foo()
final var ret2 = method.getAnnotation(Bar.class);
System.out.println(ret2); // null
final var method = A.class.getDeclaredMethod("bbb");
final var ret1 = method.getAnnotation(Foo.class);
System.out.println(ret1); // null
final var ret2 = method.getAnnotation(Bar.class);
System.out.println(ret2); // @Bar()
Annotation[] getDeclaredAnnotations ()
Returns annotations that are directly present on this element.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Foo {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Bar {
}
public class A {
@Foo
@Bar
public void aaa() {
}
}
final var method = A.class.getDeclaredMethod("aaa");
System.out.println("-- annotations --");
for (final var a : method.getDeclaredAnnotations()) {
System.out.println(a);
}
// Result
// ↓
//-- annotations --
//@Foo()
//@Bar()
Class<?> getDeclaringClass ()
Returns the Class object representing the class or interface that declares the method represented by this object.
public class Foo {
public void aaa() {
}
}
final var cls = Foo.class;
final var method = cls.getDeclaredMethod("aaa");
System.out.println(method); // public void Foo.aaa()
final var ret = method.getDeclaringClass();
System.out.println(ret); // class Foo
System.out.println(cls.equals(ret)); // true
Object getDefaultValue ()
Returns the default value for the annotation member represented by this Method instance.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Foo {
String value() default "abc";
}
public class A {
@Foo("XYZ")
public void aaa() {
}
}
final var cls = Foo.class;
final var method = cls.getDeclaredMethod("value");
System.out.println(method); // public abstract java.lang.String Foo.value()
final var ret = method.getDefaultValue();
System.out.println(ret); // abc
final var cls = A.class;
final var method = cls.getDeclaredMethod("aaa");
System.out.println(method); // public void A.aaa()
final var ret = method.getDefaultValue();
System.out.println(ret); // null
final var foo = method.getAnnotation(Foo.class);
System.out.println(foo.value()); // XYZ
Class<?>[] getExceptionTypes ()
Returns an array of Class objects that represent the types of exceptions declared to be thrown by the underlying executable represented by this object.
public class Foo<T extends Exception> {
public void aaa() throws T, IOException {
}
}
final var cls = Foo.class;
final var method = cls.getDeclaredMethod("aaa");
System.out.println(method);
System.out.println("-- getExceptionTypes --");
for (final var type : method.getExceptionTypes()) {
System.out.println(type);
}
System.out.println("-- getGenericExceptionTypes --");
for (final var type : method.getGenericExceptionTypes()) {
System.out.println(type);
}
// Result
// ↓
//public void Foo.aaa() throws java.lang.Exception,java.io.IOException
//-- getExceptionTypes --
//class java.lang.Exception
//class java.io.IOException
//-- getGenericExceptionTypes --
//T
//class java.io.IOException
Type[] getGenericExceptionTypes ()
Returns an array of Type objects that represent the exceptions declared to be thrown by this executable object.
Please see getExceptionTypes().
Type[] getGenericParameterTypes ()
Returns an array of Type objects that represent the formal parameter types, in declaration order, of the executable represented by this object.
public class Foo<T> {
public void aaa(int num, T value) {
}
}
final var cls = Foo.class;
final var method = cls.getDeclaredMethod("aaa", int.class, Object.class);
System.out.println(method);
System.out.println("-- getParameterTypes --");
for (final var type : method.getParameterTypes()) {
System.out.println(type);
}
System.out.println("-- getGenericParameterTypes --");
for (final var type : method.getGenericParameterTypes()) {
System.out.println(type);
}
// Result
// ↓
//public void Foo.aaa(int,java.lang.Object)
//-- getParameterTypes --
//int
//class java.lang.Object
//-- getGenericParameterTypes --
//int
//T
Type getGenericReturnType ()
Returns a Type object that represents the formal return type of the method represented by this Method object.
public interface Foo<T> {
T aaa();
String bbb();
}
final var cls = Foo.class;
final var method = cls.getDeclaredMethod("aaa");
System.out.println(method); // public abstract java.lang.Object Foo.aaa()
final var ret1 = method.getReturnType();
System.out.println(ret1); // class java.lang.Object
final var ret2 = method.getGenericReturnType();
System.out.println(ret2); // T
final var cls = Foo.class;
final var method = cls.getDeclaredMethod("bbb");
System.out.println(method); // public abstract java.lang.String Foo.bbb()
final var ret1 = method.getReturnType();
System.out.println(ret1); // class java.lang.String
final var ret2 = method.getGenericReturnType();
System.out.println(ret2); // class java.lang.String
int getModifiers ()
Returns the Java language modifiers for the executable represented by this object.
public class Foo {
public void aaa() {
}
protected void bbb() {
}
private void ccc() {
}
}
final var cls = Foo.class;
for (final var method : cls.getDeclaredMethods()) {
final var mod = method.getModifiers();
System.out.println(method.getName() + " : mod = " + mod);
System.out.println(" isPublic : " + Modifier.isPublic(mod));
System.out.println(" isProtected : " + Modifier.isProtected(mod));
System.out.println(" isPrivate : " + Modifier.isPrivate(mod));
}
// Result
// ↓
//aaa : mod = 1
// isPublic : true
// isProtected : false
// isPrivate : false
//bbb : mod = 4
// isPublic : false
// isProtected : true
// isPrivate : false
//ccc : mod = 2
// isPublic : false
// isProtected : false
// isPrivate : true
String getName ()
Returns the name of the method represented by this Method object, as a String.
public class Foo {
public String aaa(int num) {
return "abc";
}
}
final var cls = Foo.class;
final var method = cls.getDeclaredMethod("aaa", int.class);
System.out.println(method); // public java.lang.String Foo.aaa(int)
System.out.println(method.getName()); // aaa
Annotation[][] getParameterAnnotations ()
Returns an array of arrays of Annotations that represent the annotations on the formal parameters, in declaration order, of the Executable represented by this object.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Foo {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Bar {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Baz {
}
public class A {
public void aaa(@Foo @Bar int num, @Baz String str) {
}
}
final var method = A.class.getDeclaredMethod("aaa", int.class, String.class);
System.out.println(method);
System.out.println("-- annotations --");
for (final var a : method.getParameterAnnotations()) {
System.out.println(Arrays.toString(a));
}
// Result
// ↓
//public void A.aaa(int,java.lang.String)
//-- annotations --
//[@Foo(), @Bar()]
//[@Baz()]
int getParameterCount ()
Returns the number of formal parameters (whether explicitly declared or implicitly declared or neither) for the executable represented by this object.
public class Foo {
public void aaa() {
}
public void bbb(int num) {
}
public void ccc(int num, String str) {
}
}
final var cls = Foo.class;
final var method1 = cls.getDeclaredMethod("aaa");
System.out.println(method1); // public void Foo.aaa()
System.out.println(method1.getParameterCount()); // 0
final var method2 = cls.getDeclaredMethod("bbb", int.class);
System.out.println(method2); // public void Foo.bbb(int)
System.out.println(method2.getParameterCount()); // 1
final var method3 = cls.getDeclaredMethod("ccc", int.class, String.class);
System.out.println(method3); // public void Foo.ccc(int,java.lang.String)
System.out.println(method3.getParameterCount()); // 2
Class<?>[] getParameterTypes ()
Returns an array of Class objects that represent the formal parameter types, in declaration order, of the executable represented by this object.
Please see getGenericParameterTypes().
Class<?> getReturnType ()
Returns a Class object that represents the formal return type of the method represented by this Method object.
Please see getGenericReturnType().
TypeVariable<Method>[] getTypeParameters ()
Returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order.
public class Foo {
public <T, U> void aaa(T t, U u) {
}
}
final var method = Foo.class.getDeclaredMethod("aaa", Object.class, Object.class);
System.out.println(method);
System.out.println("-- parameters --");
for (final var param : method.getTypeParameters()) {
System.out.println(param);
}
// Result
// ↓
//public void Foo.aaa(java.lang.Object,java.lang.Object)
//-- parameters --
//T
//U
int hashCode ()
Returns a hashcode for this Method.
public static class Foo {
public void aaa() {
}
public void aaa(int num) {
}
public void bbb() {
}
}
final var cls = Foo.class;
final var ret1 = cls.getDeclaredMethod("aaa").hashCode();
System.out.println(ret1); // -409596127
final var ret2 = cls.getDeclaredMethod("aaa", int.class).hashCode();
System.out.println(ret2); // -409596127
final var ret3 = cls.getDeclaredMethod("bbb").hashCode();
System.out.println(ret3); // -409597118
Object invoke (Object obj, Object... args)
Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.
public class AccessTest2 {
public String aaa() {
return "abc";
}
private int sum(int a, int b) {
return a + b;
}
}
final var cls = AccessTest2.class;
final var obj = new AccessTest2();
final var method = cls.getDeclaredMethod("aaa");
System.out.println(method); // public java.lang.String AccessTest2.aaa()
System.out.println(method.canAccess(obj)); // true
final var ret = method.invoke(obj);
System.out.println(ret); // abc
final var cls = AccessTest2.class;
final var obj = new AccessTest2();
final var method = cls.getDeclaredMethod("sum", int.class, int.class);
System.out.println(method); // private int AccessTest2.sum(int,int)
System.out.println(method.canAccess(obj)); // false
//method.invoke(obj, 20, 30); // IllegalAccessException
System.out.println(method.trySetAccessible()); // true
System.out.println(method.canAccess(obj)); // true
final var ret = method.invoke(obj, 20, 30);
System.out.println(ret); // 50
boolean isBridge ()
Returns true if this method is a bridge method; returns false otherwise.
public class Foo {
@Override
public Foo clone() {
throw new UnsupportedOperationException();
}
}
final var cls = Foo.class;
System.out.println("-- methods --");
for (final var method : cls.getDeclaredMethods()) {
System.out.println(method);
System.out.println(method.isBridge());
}
// Result
// ↓
//-- methods --
//public Foo Foo.clone()
//false
//public java.lang.Object Foo.clone() throws java.lang.CloneNotSupportedException
//true
boolean isDefault ()
Returns true if this method is a default method; returns false otherwise.
public interface Foo {
void aaa();
default void bbb() {
}
}
final var cls = Foo.class;
final var method1 = cls.getDeclaredMethod("aaa");
System.out.println(method1); // public abstract void Foo.aaa()
System.out.println(method1.isDefault()); // false
final var method2 = cls.getDeclaredMethod("bbb");
System.out.println(method2); // public default void Foo.bbb()
System.out.println(method2.isDefault()); // true
boolean isSynthetic ()
Returns true if this executable is a synthetic construct; returns false otherwise.
public class IsSyntheticTest {
interface Foo<T> {
void aaa(T value);
}
class Bar implements Foo<String> {
@Override
public void aaa(String value) {
}
}
public static void main(String[] args) {
final var cls = Bar.class;
for (final var method : cls.getDeclaredMethods()) {
System.out.println(method);
System.out.println(method.isSynthetic());
}
// Result
// ↓
//public void IsSyntheticTest$Bar.aaa(java.lang.String)
//false
//public void IsSyntheticTest$Bar.aaa(java.lang.Object)
//true
}
}
boolean isVarArgs ()
Returns true if this executable was declared to take a variable number of arguments; returns false otherwise.
public class Foo {
public void aaa(int num) {
}
public void bbb(int num, String... args) {
}
}
final var method = Foo.class.getDeclaredMethod("aaa", int.class);
System.out.println(method); // public void Foo.aaa(int)
System.out.println(method.isVarArgs()); // false
final var method = Foo.class.getDeclaredMethod("bbb", int.class, String[].class);
System.out.println(method); // public void Foo.bbb(int,java.lang.String[])
System.out.println(method.isVarArgs()); // true
void setAccessible (boolean flag)
Set the accessible flag for this reflected object to the indicated boolean value.
public class AccessTest {
private int sum(int a, int b) {
return a + b;
}
}
final var cls = AccessTest.class;
final var obj = new AccessTest();
final var method = cls.getDeclaredMethod("sum", int.class, int.class);
System.out.println(method.canAccess(obj)); // false
method.setAccessible(true);
System.out.println(method.canAccess(obj)); // true
method.setAccessible(false);
System.out.println(method.canAccess(obj)); // false
String toGenericString ()
Returns a string describing this Method, including type parameters.
public class Foo<T> {
public void aaa(int num) {
}
public void bbb(T value) {
}
}
final var method = Foo.class.getDeclaredMethod("aaa", int.class);
final var ret1 = method.toGenericString();
System.out.println(ret1); // public void Foo.aaa(int)
final var ret2 = method.toString();
System.out.println(ret2); // public void Foo.aaa(int)
final var method = Foo.class.getDeclaredMethod("bbb", Object.class);
final var ret1 = method.toGenericString();
System.out.println(ret1); // public void Foo.bbb(T)
final var ret2 = method.toString();
System.out.println(ret2); // public void Foo.bbb(java.lang.Object)
String toString ()
Returns a string describing this Method.
Please see toGenericString().
Methods declared in Executable
getAnnotatedExceptionTypes, getAnnotatedParameterTypes, getAnnotatedReceiverType, getAnnotationsByType, getParameters
Please see the link below.
Methods declared in AccessibleObject
canAccess, getAnnotations, getDeclaredAnnotation, getDeclaredAnnotationsByType, isAccessible, isAnnotationPresent, setAccessible, trySetAccessible
Please see the link below.
Methods declared in AnnotatedElement
getAnnotations, getDeclaredAnnotation, getDeclaredAnnotationsByType, isAnnotationPresent
Please see the link below.