Search This Blog

Thursday, 14 August 2014

Get Class name in Java using Reflection API - JAVA

This program shows how to Get Class name of a class you don't know about using reflection API in Java.

AnotherClass.java

public class AnotherClass {
 public int x;

 public int getX() {
  return x;
 }
}

MainClass.java

/**
 * Get Class name in Java - Reflection API
 *
 * How to get class name when you don't know what the class is in Java
 */
public class MainClass {
 
 public static void main(String[] args){
  AnotherClass obj = new AnotherClass();
  
  Class c = obj.getClass();
  System.out.println(c.getName()); //Complete Class name
  System.out.println(c.getSimpleName()); // Class name, i.e. AnotherClass
 }
}

No comments:

Post a Comment