Check whether the specified class contains a field matching the specified name in Java

Description

The following code shows how to check whether the specified class contains a field matching the specified name.

Example


/*w ww .  j  a  v a2 s. c  om*/
public class Main {
  public static void  main(String args[]) {
    System.out.println(containsField(String.class,"asdf"));
  }
  public static boolean containsField(Class<?> clazz, String fieldName) {
    try {
      clazz.getDeclaredField( fieldName );
      return true;
    }
    catch ( NoSuchFieldException e ) {
      return false;
    }
  }
}




















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy