黑马程序员技术交流社区
标题:
在网上看到的一道题目
[打印本页]
作者:
马也keyboard
时间:
2015-6-23 23:06
标题:
在网上看到的一道题目
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
/**
* 存在一个JavaBean,它包含以下几种可能的属性:
1:boolean/Boolean
2:int/Integer
3:String
4:double/Double
属性名未知,现在要给这些属性设置默认值,以下是要求的默认值:
String类型的默认值为字符串 www.itheima.com
int/Integer类型的默认值为100
boolean/Boolean类型的默认值为true
double/Double的默认值为0.01D.
只需要设置带有getXxx/isXxx/setXxx方法的属性,非JavaBean属性不设置,请用代码实现
* @author hp
*
*/
public class test5 {
public static void property(JavaBean java) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
Class className = java.getClass();
BeanInfo bean = Introspector.getBeanInfo(className);
PropertyDescriptor[] properties = bean.getPropertyDescriptors();
for(PropertyDescriptor pd : properties)
{
String name = pd.getName();
Class type = pd.getPropertyType();
Method get = pd.getReadMethod();
Method set = pd.getWriteMethod();
if(!name.equals("class"))
{
if(get != null)
{
if(type == boolean.class || type == Boolean.TYPE)
{
set.invoke(java, true);
}
if(type == int.class || type == Integer.TYPE)
{
set.invoke(java, 100);
}
if(type == String.class)
{
set.invoke(java, "www.itheima.com");
}
if(type == double.class || type == Double.TYPE)
{
set.invoke(java, 0.01d);
}
}
}
}
}
public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException
{
JavaBean java = new JavaBean();
property(java);
System.out.println(java.getName());
System.out.println(java.getNum());
System.out.println(java.getFlag());
System.out.println(java.getTag());
}
}
class JavaBean
{
private String name;
private int num;
public boolean flag;
private double tag;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public boolean getFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public double getTag() {
return tag;
}
public void setTag(double tag) {
this.tag = tag;
}
}
复制代码
在毕老师的视频里没有看到,好像是张老师讲过
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2