Java Class reflection get class name and super class name

Introduction

The following program demonstrates getClass() inherited from Object and getSuperclass() from Class:

// Demonstrate Run-Time Type Information.
class X {// w  w w .j  a  v a 2 s  . co m
  int a;
  float b;
}

class Y extends X {
  double c;
}

public class Main {
  public static void main(String args[]) {
    X x = new X();
    Y y = new Y();
    Class<?> clObj;

    clObj = x.getClass(); // get Class reference
    System.out.println("x is object of type: " +
                       clObj.getName());

    clObj = y.getClass(); // get Class reference
    System.out.println("y is object of type: " +
                       clObj.getName());
    clObj = clObj.getSuperclass();
    System.out.println("y's superclass is " +
                       clObj.getName());
  }
}



PreviousNext

Related