package cn.com.chapter1.technolgy;
/**
* java 反射操作无参构造方法
*/
import java.lang.reflect.Method;
public class TestDemo2 {
public static void main(String[] args)throws Exception{
Class?> cls=Class.forName('cn.com.chapter1.technolgy.Book3');
Object obj=cls.newInstance();
String s1='title';
String s2='price';
Method setMethodTitle=cls.getMethod('set'+initCap(s1), String.class);
Method setMethodPrice=cls.getMethod('set'+initCap(s2), double.class);
Method getMethodTitle=cls.getMethod('get'+initCap(s1));
Method getMethodPrice=cls.getMethod('get'+initCap(s2));
setMethodTitle.invoke(obj, '反射操作方法');
setMethodPrice.invoke(obj, 98);
System.out.println(getMethodTitle.invoke(obj));
System.out.println(getMethodPrice.invoke(obj));
}
public static String initCap(String str)
{
return str.substring(0,1).toUpperCase()+str.substring(1);
}
}
class Book3
{
private String title;
private double price;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString()
{
return 'title='+this.title+',price='+this.price;
}
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。