The Class Class
Home ] Up ] [ The Class Class ] Examining a Class ] Array Name Encodings ] Creating a Class Instance ] The Reflection Classes ]

 

 

There exists a class in Java called -- appropriately, but perhaps confusingly -- Class. This class maintains run-time type information about the components of your program while it is running.

Class Class does not have a public constructor. Instead, you obtain an instance of this class in one of a number of ways. For example, by using:

  • the getClass() method in class Object
String s;
...
Class c = s.getClass();
  • the forName() method in class Class
Class c = Class.forName("java.lang.String");
  • the class operator
Class c1 = String.class;
Class c2 = int.class;
Class c3 = Double[].class;

Class has many useful methods you can use to obtain information about the element it describes. 

For example, assume we have the following classes and interfaces:

package reflection;

public class Person
{
    public Person()
    {
    }
    
    public Person(String name, 
                  int age)
    {
        m_name = name;
        m_age  = age;
    }
    
    public void init(String name, 
                     int age)
    {
        m_name = name;
        m_age  = age;
    }

    public String getName()
    {
        return m_name;
    }
    
    public int getAge()
    {
        return m_age;
    }
    
    /////// Data ////////
    private String  m_name;
    private int     m_age;
}
package reflection;

public interface Firer
{
    public void fire(Employee emp);
}
package reflection;

public interface Hirer
{
    public void hire(Employee emp);
}
package reflection;

public interface HirerFirer
    extends Hirer, Firer
{
}
package reflection;

public class Employee
    extends Person
{
    public Employee()
    {
    }
    
    public Employee(String name,   
                    int  age, 
                    double salary, 
                    long id)
    {
        super(name, age);
        m_salary = salary;
        m_id = id;
    }
    
    public void init(String name,   
                     int age,
                     double salary, 
                     long id)
    {
        super.init(name, age);
        m_salary = salary;
        m_id = id;
    }
    
    public double getSalary()
    {
        return m_salary;
    }
    
    public long getId()
    {
        return m_id;
    }
    
    /////// Data ///////
    private double m_salary;
    private long   m_id;
}
package reflection;

public class Manager
    extends Employee
    implements Hirer, Firer
{
    public Manager()
    {
    }
    
    public Manager(String name,   
                   int  age,
                   double salary, 
                   long id)
    {
        super(name, age, salary, id);
    }
    
    public void hire(Employee emp)
    {
        // Details...
    }

    public void fire(Employee emp)
    {
        // Details...
    }
}
 
The page was last updated February 19, 2008