反射
例1
public class Person {
public void sleep(){
System.out.println("人睡觉");
}
}
public class Student extends Person{
@Override
public void sleep() {
System.out.println("学生睡觉");
}
}
public class Teacher extends Person{
@Override
public void sleep() {
System.out.println("老师睡觉");
}
}
public class Worker extends Person{
@Override
public void sleep() {
System.out.println("工人睡觉");
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class Factory {
public static Person creatPerson(){
Person person=null; //定义要返回的变量
Properties p=new Properties(); //创建一个带有指定默认值的空属性列表
try {
p.load(new FileInputStream("config.properties"));//从输入流中读取属性列表(键和元素对).
String clazzName=p.getProperty("vocation");//用指定的键在此属性列表中搜索属性
Class clazz=Class.forName(clazzName);//返回与带有给定字符串名的类或接口相关联的 Class 对象
person=(Person) clazz.newInstance();//newInstance创建此 Class 对象所表示的类的一个新实例
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return person;
}
}
public class FactoryTest {
public static void main(String[] args) {
Person person=Factory.creatPerson();
person.sleep();
}
}
config.properties文件:vocation=com.lingzhuo.reflect.Teacher
config.properties文件:vocation=com.lingzhuo.reflect.Worker
例2
public class Student {
private int age;
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
}
import java.lang.reflect.Field;
public class RelfectTest {
public static void main(String[] args) {
Class<Student> clazz=Student.class;//就是由已有的类产生他的抽象类,Class<Student>即Student的抽象类
// Field[] fields=clazz.getFields();//以数组形式返回所有公共属性,注意是公共属性(public)
Field[] fields=clazz.getDeclaredFields();//以数组形式返回所有的属性
for (Field field : fields) {
System.out.println(field.getName());//返回的属性名称
System.out.println(field.getType().getName());//返回属性的类型名称
System.out.println(field.getModifiers());//返回属性修饰符的整数表示形势
}
Student zhangsan=new Student();
try {
Field age = clazz.getDeclaredField("age");//得到指定名称的属性age
age.setAccessible(true); //取消java访问修饰符检查
age.set(zhangsan, 18); //将对象zhangsan的age属性值更改为18
age.setAccessible(false); //恢复检查
System.out.println(zhangsan.getAge()); //输出age值
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
注解
例1
import java.lang.reflect.Field;
public class Student {
@StudentAnnotation(18)
private int age;
public Student(){
//反射
Class clazz=Student.class;//得到student类的Class的对象
try {
Field field=clazz.getDeclaredField("age");//得到age属性
StudentAnnotation sa=field.getAnnotation(StudentAnnotation.class);
//得到age属性的StudentAnnotation注解,如果没有返回null
if(sa!=null){
int i=sa.value();//获得属性的默认值
field.setAccessible(true);//设置为不检查属性的访问修饰符
field.set(this, i);//this指的是Student的对象
//将Student的对象的age属性修改为i
field.setAccessible(false);//设置属性的访问修饰符检查
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public String clazz;
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)//此范围内的注解可以执行
@Target(ElementType.FIELD)//表示此注解只能用到属性上
public @interface StudentAnnotation {
int value();//表明此注解可以注解一个int值
}
public class Test {
public static void main(String[] args) {
Student zhangsan=new Student();
System.out.println(zhangsan.getAge());
}
}
例2
import java.lang.reflect.Field;
public class Clazz {
@TeacherAnnotation(age=20,name="张三")
private Teacher javaTeacher;
@TeacherAnnotation(age=22,name="李四")
private Teacher englishTeacher;
@TeacherAnnotation(name="王五")
private Teacher mathTeacher;
private int clazzNum;
private String name;
public Clazz(){
Class clazz=Clazz.class;
Field[] fields=clazz.getDeclaredFields();
//得到clazz所有的属性
for(Field field:fields){
TeacherAnnotation ta=field.getAnnotation(TeacherAnnotation.class);
//得到TeacherAnnotation注解,如果没有返回null
if(ta==null){
continue;//如果为null跳出
}else{
int age=ta.age();//得到该注解的age值,如果没有使用默认值
String name=ta.name();//得到该注解的name值
Teacher teacher=new Teacher();
teacher.setAge(age);
teacher.setName(name);//根据注解的值创建新的对象
field.setAccessible(true);//设置为不检查属性的访问修饰符
try {
field.set(this,teacher);//将这个teacher对象赋值给此班级对象的该属性
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
field.setAccessible(false);
}
}
}
public Teacher getJavaTeacher() {
return javaTeacher;
}
public void setJavaTeacher(Teacher javaTeacher) {
this.javaTeacher = javaTeacher;
}
public Teacher getEnglishTeacher() {
return englishTeacher;
}
public void setEnglishTeacher(Teacher englishTeacher) {
this.englishTeacher = englishTeacher;
}
public Teacher getMathTeacher() {
return mathTeacher;
}
public void setMathTeacher(Teacher mathTeacher) {
this.mathTeacher = mathTeacher;
}
public int getClazzNum() {
return clazzNum;
}
public void setClazzNum(int clazzNum) {
this.clazzNum = clazzNum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Teacher {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TeacherAnnotation {
int age() default 19;//如果age在注解中没有声明则使用默认default值
String name();
}
public class Test {
public static void main(String[] args) {
Clazz clazz=new Clazz();
System.out.println(clazz.getEnglishTeacher().getName()+clazz.getEnglishTeacher().getAge());
System.out.println(clazz.getMathTeacher().getName()+clazz.getMathTeacher().getAge());
}
}