reflection
Get methods return type
This is an example of how to get the return type of a classe’s methods. To get the return type of a classe’s methods one should perform the following steps:
- Get the array of Method objects reflecting all the methods declared by the class, using
getDeclaredMethods()
API method of Class. This includes public, protected, default (package) access, and private methods, but excludes inherited methods. The elements in the array returned are not sorted and are not in any particular order. This method returns an array of length 0 if the class or interface declares no methods, or if this Class object represents a primitive type, an array class, or void. - For all elements in the array get the return type for the method each object represents, using
getReturnType()
API method of Method.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; public class GetReturnType { public static void main(String args[]){ Class<?> clazz = java.lang.ThreadLocal.class; Method[] methods; // return class and super class methods methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++){ System.out.println(methods[i] + ", return type :" + methods[i].getReturnType()); } } }
Output:
public java.lang.Object java.lang.ThreadLocal.get(), return type :class java.lang.Object
public void java.lang.ThreadLocal.remove(), return type :void
static java.lang.ThreadLocal$ThreadLocalMap java.lang.ThreadLocal.createInheritedMap(java.lang.ThreadLocal$ThreadLocalMap), return type :class java.lang.ThreadLocal$ThreadLocalMap
static int java.lang.ThreadLocal.access$400(java.lang.ThreadLocal), return type :int
public void java.lang.ThreadLocal.set(java.lang.Object), return type :void
private java.lang.Object java.lang.ThreadLocal.setInitialValue(), return type :class java.lang.Object
java.lang.Object java.lang.ThreadLocal.childValue(java.lang.Object), return type :class java.lang.Object
void java.lang.ThreadLocal.createMap(java.lang.Thread,java.lang.Object), return type :void
java.lang.ThreadLocal$ThreadLocalMap java.lang.ThreadLocal.getMap(java.lang.Thread), return type :class java.lang.ThreadLocal$ThreadLocalMap
protected java.lang.Object java.lang.ThreadLocal.initialValue(), return type :class java.lang.Object
private static int java.lang.ThreadLocal.nextHashCode(), return type :int
This was an example of how to get the return type of a classe’s methods in Java.