不是程序本身,但是可以被其他程序读取
元注解是用于定义注解的注解
包括@Retention、@Target、@Inherited、@Documented
@interface用来自定义注解
@Target({ElementType.METHOD,ElementType.TYPE})
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
// 为注解定义属性
String value();//书名
double price() default 100;//价格,默认值为 100
String[] authors();//多位作者
}
Java语言通过反射可以获得类似动态语言的特性
动态语言就是在运行时可以改变其结构的语言
是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。
经典应用:AOP
有很大的灵活性,动态的创建对象
使用反射创建对象执行慢于相同的不借助反射的操作
Class c=Class.forName("Java.lang.String")//Class类自带的静态方法获取类
Class c=String.class;//通过具体的类进行获取类
Class c=string.getClass();//通过实例获取类
Person类:
public class Person {
private int num;
public Person() {
}
public Person(int num){
this.num=num;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
User类:
public class User extends Person{
private int no;
private String name;
public User(){
}
private User(int no, String name) {
this.no = no;
this.name = name;
}
private int getNo() {
return no;
}
private void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
测试类:
public class ReDemo {
public static void main(String[] args) throws Exception {
Class c=User.class;
Field[]fields1=c.getFields();//获取本类的public属性
Field[]fields2=c.getDeclaredFields();//获取本类的全部属性
for(Field f:fields2){
System.out.println(f);
}
Method[] methods1 = c.getMethods();//获取本类以及父类的public方法
Method[] methods2 = c.getDeclaredMethods();//获取本类的全部方法
for(Method m:methods2){
System.out.println(m);
}
User user1 = (User)c.newInstance();//实例采取的是默认构造器
Method setName=c.getDeclaredMethod("setName", String.class);
setName.invoke(user1,"zjr");
System.out.println(user1.getName());
Constructor con=c.getDeclaredConstructor(int.class,String.class);
con.setAccessible(true);//允许访问私有属性
User user2 = (User)con.newInstance(1, "zjr");
System.out.println(user2.getName());
}
}