Bean:组件
javaBean:java组件
条件:类必须是具体的和公共的
并且具有无参数的构造器
给定的所有属性必须私有,且提供get和set方法,设置get和set方法时候,必须把属性的首字母大写在属性名前添加get和set字样
通过自省机制发现和操作这些JavaBean的属性
方法的接口,都存于java.bean包下面
bean组件示例:
public class Bean {
private String name;
private int age;
private String sex;
private String hobbit;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getHobbit() {
return hobbit;
}
public void setHobbit(String hobbit) {
this.hobbit = hobbit;
}
@Override
public String toString() {
return("name="+name+",age="+age+",sex="+sex+",hobbit="+hobbit);
}
}
toString方法是用来检验是否操作成功
对bean进行操作:
public class Main {
public static void main(String[] args) {
Bean bean =new Bean();
try {
BeanInfo beanInfo=Introspector.getBeanInfo(bean.getClass());
//获取属性描述
PropertyDescriptor[] pro=beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : pro) {
//获取属性名
String name=propertyDescriptor.getName();
//获取get方法
Method getMethod=propertyDescriptor.getReadMethod();
//获取set方法
Method setMethod=propertyDescriptor.getWriteMethod();
if("name".equals(name)){
setMethod.invoke(bean, "xiaohei");
}
else if("age".equals(name)){
setMethod.invoke(bean,15);
}
else if("sex".equals(name)){
setMethod.invoke(bean, "nan");
}
else if("hobbit".equals(name)){
setMethod.invoke(bean, "xx");
}
}
System.out.println(bean.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
对于properties对象:
先在目录下创建properties文件
classname=\u5C0F\u9EC4
name=xiaohei
age=16
sex=gong
hobbit=xx
对象的读取:
利用io流读取:
public class Test {
static Properties pro=new Properties();
static{
InputStream is;
try {
is = new FileInputStream("bean.properties");
pro.load(is);
System.out.println(pro.getProperty("name"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
}
}