Return Retrurns the Type of the given Field or Method in Java

Description

The following code shows how to return Retrurns the Type of the given Field or Method.

Example


//  ww  w. ja va 2  s.  co  m
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

public class Main {
  public static void  main(String args[]) {
    Field fields[] = String.class.getDeclaredFields();
    for (Field fld : fields)
      System.out.println(typeOf(fld) );
  }
  public static Type typeOf(Member member) {
    if ( member instanceof Field ) {
      return ( ( Field ) member ).getGenericType();
    }
    if ( member instanceof Method ) {
      return ( ( Method ) member ).getGenericReturnType();
    }
    throw new IllegalArgumentException( "Member " + member + " is neither a field nor a method" );
  }

}




















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy