一、正确的输出应当是什么?
if(true){
System.out.print(1);
}else if(true){
System.out.print(2);
}else{
System.out.print(3);
}
二、反射技术
import java.lang.reflect.Field;
public class Test
{
public static void main(String[]args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
{
Person person =new Person();
person.setName("VipMao");
person.setAge(34);
person.setSex("男");
//通过Class.getDeclaredField(String name)获取类或接口的指定属性值。
Field f1=person.getClass().getDeclaredField("name");
System.out.println("-----Class.getDeclaredField(String name)用法-------");
System.out.println(f1.get(person));
System.out.println("-----Class.getDeclaredFields()用法-------");
//通过Class.getDeclaredFields()获取类或接口的指定属性值。
Field []f2=person.getClass().getDeclaredFields();
for(Field field:f2)
{
field.setAccessible(true);
System.out.println(field.getName()+":"+field.get(person));
}
//修改属性值
System.out.println("----修改name属性------");
f1.set(person, "Maoge");
//修改后再遍历各属性的值
Field []f3=person.getClass().getDeclaredFields();
for(Field fields:f3)
{
fields.setAccessible(true);
System.out.println(fields.get(person));
}
}
}
class Person{
String name;
int age;
String sex;
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;
}
}