Reflection
Main.java
package com.mtit.Labs;
import
java.lang.reflect.Modifier;
public class Task1 {
public static void main(String[] args) {
try {
Class<?>
clazz = Class.forName("com.mtit.Labs.Task1");
System.out.println(clazz.getSimpleName()); // Task1
System.out.println(clazz.getName()); // com.mtit.Labs.Task1
System.out.println(clazz.getPackage()); // package com.mtit.Labs
System.out.println(clazz.getModifiers()); // 1
System.out.println(clazz.getDeclaredMethod("main", String[].class)); // public static void
com.mtit.Labs.Task1.main(java.lang.String[])
System.out.println(Modifier.toString(clazz.getDeclaredMethod(
"main", String[].class).getModifiers())); // public static
}
catch
(ClassNotFoundException | NoSuchMethodException
|
SecurityException e) {
e.printStackTrace();
}
}
Final
Output
Task1
com.mtit.Labs.Task1
package com.mtit.Labs
1
public static void
com.mtit.Labs.Task1.main(java.lang.String[])
public static
Task 2
Books.java
package com.mtit.lab_task_2;
public class Books {
private String bookName = "Head First
design patterns";
public int bookCount = 20;
public String [] authors = {"Eric
Freeman", "Elisabeth Freeman"};
public double price;
public String getBookName()
{
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getBookCount() {
return bookCount;
}
public void setBookCount(int bookCount) {
this.bookCount = bookCount;
}
public String[]
getAuthors() {
return authors;
}
public void setAuthors(String[] authors) {
this.authors = authors;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
Main.java
package com.mtit.lab_task_2;
import
java.lang.reflect.Field;
import java.util.Arrays;
public class Task2_Main {
public static void main(String[] args) {
try{
Books
b = new Books();
Class<?>
clazz = Class.forName("com.mtit.lab_task_2.Books");
Field
pri_field_1 = clazz.getDeclaredField("bookName"); //use getDeclaredField since bookName is a private field
Field
pField = clazz.getField("price"); //can use getField or getDeclaredField since price is a public field
Field
pri_field_1 = clazz.getField("bookCount");
pri_field_1.setAccessible(true); //private fields have to be true to 'get' or 'set', them
pField.setAccessible(true);
pField.set(b , 2187.5);
System.out.println(pri_field_1.getName()+" = "+pri_field_1.get(b)); //bookName = Head First design patterns
System.out.println("Authors =
" +
Arrays.asList((String [])clazz.getField("authors").get(b))); //Authors = [Eric Freeman, Elisabeth Freeman]
System.out.println(publicField.getName()+" = "+publicField.get(b)); //bookCount = 20
System.out.println(pField.getName()+" = "+pField.get(b)); //price = 2187.5
}catch(ClassNotFoundException
| SecurityException | NoSuchFieldException | IllegalArgumentException |
IllegalAccessException e){
e.printStackTrace();
}
}
}
Final
Output
bookName = Head First design patterns
Authors = [Eric Freeman, Elisabeth
Freeman]
bookCount = 20
price = 2187.5
Task 3
Employee.java
package com.mtit.Task_3;
public class Employee {
private String eid = "E001";
String
ename = "Anura";
public String address = "Colombo";
protected double salary = 60_000.00;
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getAddress()
{
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
private String display(String
eid, String ename, String address,
double salary) {
System.out.println("Method
invoked successfully");
return eid + ", " + ename + ", " + address + ", " + salary;
// note
this is a private method!
}
}
Main.java
package com.mtit.Task_3;
import
java.lang.reflect.Method;
import
java.lang.reflect.Modifier;
public class Task3_Main {
public static void main(String[] args) {
// TODO Auto-generated
method stub
try {
Class<?>
clazz = Class.forName("com.mtit.Task_3.Employee");
Method[]
methods = clazz.getDeclaredMethods();
// methods are returned as Method[] array
for(Method method:methods)
{
System.out.println("Modifiers
=>"+Modifier.toString(method.getModifiers()));
System.out.print("|| Return
type =>"+method.getReturnType());
System.out.println("|| Name=>
"+method.getName());
if(method.getParameterTypes().length>0)// get the length of the parameters. if greater than 0
then there are parameters
{
System.out.print("||
Parameters=> ");
for(Class<?> t:method.getParameterTypes())//getParameterTypes() returns a Class<?>[] array.
{
System.out.println(t.getSimpleName()+" ");// we are accessing each element and get the simple name
}
}
}
}
catch
(ClassNotFoundException e) {
// TODO Auto-generated
catch block
e.printStackTrace();
}
}
}
Special method invocation method
package com.mtit.Task_3;
import java.lang.reflect.InvocationTargetException;
import
java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Task3_Main {
public static void main(String[] args) {
// TODO Auto-generated
method stub
try {
Employee
employee = new Employee();
//set types of parameters to be passed for the method
Class[]
parameters = new Class[4];
parameters[0] = String.class;
parameters[1] = String.class;
parameters[2] = String.class;
parameters[3] = Double.TYPE;
//get display() method of the Employee class
Method
m = employee.getClass().getDeclaredMethod("display", parameters);
m.setAccessible(true); // display is a private method!!!!
//invoke method with passing parameters
String
result = (String) m.invoke(employee, "e100","upul","malabe",80000.00);
System.out.println(result);
}
catch
(NoSuchMethodException | SecurityException | IllegalAccessException |
InvocationTargetException e) {
// TODO Auto-generated
catch block
e.printStackTrace();
}
}
}
Annotation Task
Interface Test.java
package com.mtit.Task_4;
import
java.lang.annotation.Documented;
import
java.lang.annotation.ElementType;
import
java.lang.annotation.Inherited;
import
java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import
java.lang.annotation.Target;
@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
int priority() default 1;
String
description();
String
[] groups() default "";
String
[] dependsOnMethods() default "";
}
TestAnnotation.java class
package com.mtit.Task_4;
public class TestAnnotation {
@Test(priority = 2,
dependsOnMethods = {"testCase2", "testCase3"},
description
= "This
represents annotation test case1", groups = {"com.MTIT"})
public String testCase1(){
return "Annotation
test case 1";
}
@Test(description = "This
represents annotation test case2", groups = {"com.MTIT"})
public String testCase2(){
return "Test case
2";
}
@Test(description = "This
represents annotation test case3")
public String testCase3(){
return "Test case
3";
}
}
Task4_main.java
package com.mtit.Task_4;
import
java.lang.annotation.Annotation;
import
java.lang.reflect.Method;
import java.util.Arrays;
public class Task4_main {
public static void main(String[] args) {
// TODO Auto-generated
method stub
try{
Method
method = new
TestAnnotation().getClass().getDeclaredMethod("testCase1");
Annotation[]
annotaions = method.getDeclaredAnnotations();
for(Annotation annotation:annotaions){
Test testAnnt = (Test)annotation;
System.out.println("Priority =
" +
testAnnt.priority());
System.out.println("Description =
" +
testAnnt.description());
System.out.println("Depends on
methods = " + Arrays.toString(testAnnt.dependsOnMethods()));
System.out.println("Groups =
" +
Arrays.toString(testAnnt.groups()));
}
}catch(NoSuchMethodException
| SecurityException e){
e.printStackTrace();
}
}
}
No comments:
Post a Comment