September 27, 2017

How to use same method for different objects in java

/**
 *  Main class
 */
package com.belazy.generics;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author belazy
 * @param <T>
 *
 */
public class GenericMethodClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
GenericMethodClass g = new GenericMethodClass();

String type ="type";

Employee emp = new Employee();
Student stud = new Student();
g.returnText(emp, type);
g.returnText(stud, type);

}



public <T> String returnText(T element , String type){
String value = null;
try {
Class thisClass = element.getClass();

type = element.getClass().toString();
Method method = thisClass.getMethod("getName");
System.out.println("method with getName "+method.getName());
System.out.println(method.invoke(element));
if(method.invoke(element).toString().equalsIgnoreCase("type")){
System.out.println("inside if ");
Method method2 = thisClass.getMethod("getText");
System.out.println(method2.invoke(element));
value = method2.invoke(element).toString();
}


} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


System.out.println(type);
return value;


}

}

Student class

/**
 *
 */
package com.belazy.generics;

/**
 * @author belazy
 *
 */
public class Student {

String name = "type";
String text = "Student Type";
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the text
*/
public String getText() {
return text;
}
/**
* @param text the text to set
*/
public void setText(String text) {
this.text = text;
}



}

Employee Class

/**
 * 
 */
package com.belazy.generics;

/**
 * @author belazy
 *
 */
public class Employee {
String name = "type";
String text = "employee Type";
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the text
*/
public String getText() {
return text;
}
/**
* @param text the text to set
*/
public void setText(String text) {
this.text = text;
}

}


No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments