Monday, July 30, 2012

JAVA REFLECTION

Code:


I have the following class.



package pd.tutorials.practice;

public class Employee {
public String name;
public double salary;
public int age;
public String employeeId;
static{
System.out.println("static block called");
}
public Employee()
{
System.out.println("Employee constructor called");
}
public Employee(String name1, double salary, int age, String employeeId)
{
name = name1;
this.salary = salary;
this.age = age;
this.employeeId = employeeId;
}
//overriden method
public String toString() {
return name + ", " + salary + ", " + age + ", " + employeeId;
}

}



package pd.tutorials.practice;


public class TryCollections {

public static void main(String a[]) {
try {
                        // loads the class. calls static block
Class.forName("pd.tutorials.Employee");
//define type of constructor a class may have
Class[] paramType = {String.class, Double.TYPE, 
Integer.TYPE, String.class};
//asking if the class has the constructor type defined above
Constructor<Employee> con = Employee.class.getConstructor(paramType);
System.out.println("No error means...found the constructor");
//if constructor is found, create values to pass to constructor
Object [] paramValues = {"Pratik Dave",
new Double(10000), 
30,
"539622"
};
// calls the constructor
Employee emp = con.newInstance(paramValues);
System.out.println(emp.age);
} catch (Exception ex) {
ex.printStackTrace();
}

}

}

No comments:

Post a Comment