反射
获取Class对象三种方式
第一种方式:类.class
第二种方式:对象.getClass()
第三种方式:Class.forName
在一个JVM中,一种类,只会有一个类对象存在。所以以上三种方式取出来的类对象,都是一样的。
通过反射机制创建对象
package reflection;
import java.lang.reflect.Constructor;
import charactor.Hero;
public class TestReflection {
public static void main(String[] args) {
Hero h1 =new Hero();
h1.name = "teemo";
System.out.println(h1);
try {
String className = "charactor.Hero";
Class pClass=Class.forName(className);
Constructor c= pClass.getConstructor();
Hero h2= (Hero) c.newInstance();
h2.name="gareen";
System.out.println(h2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
通过反射修改属性的值
package reflection;
import java.lang.reflect.Field;
import charactor.Hero;
public class TestReflection {
public static void main(String[] args) {
Hero h =new Hero();
h.name = "garen";
try {
Field f1= h.getClass().getDeclaredField("name");
f1.set(h, "teemo");
System.out.println(h.name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
首先为Hero的name属性,增加setter和getter
通过反射机制调用Hero的setName
package reflection;
import java.lang.reflect.Method;
import charactor.Hero;
public class TestReflection {
public static void main(String[] args) {
Hero h = new Hero();
try {
Method m = h.getClass().getMethod("setName", String.class);
m.invoke(h, "盖伦");
System.out.println(h.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
反射机制的用处(自己理解):一般和Spring一起使用,之前调用业务,必须修改代码重新编译,用反射的话只需要修改Spring的配置文件即可。
这么看反射也没有当初觉得的那么难懂
注解
内置注解没啥用,一般用自定义注解
元注解有这么几种:
@Target
@Retention
@Inherited
@Documented
@Repeatable (java1.8 新增)
根据注解的作用域@Retention,注解分为
RetentionPolicy.SOURCE: Java源文件上的注解
RetentionPolicy.CLASS: Class类文件上的注解
RetentionPolicy.RUNTIME: 运行时的注解
按照注解的来源,也是分为3类
- 内置注解 如@Override ,@Deprecated 等等
- 第三方注解,如Hibernate, Struts等等
- 自定义注解,如仿hibernate的自定义注解
在工作中,大部分都是使用第三方注解, 当然第三方注解本身就是自定义注解。
明天看看”白盒单元测试”,上课没听,现在又得补,害
Original: https://www.cnblogs.com/GeniusWang/p/15644222.html
Author: Genius_Wang
Title: 6.18(反射和注解—>反射机制的作用)
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/583156/
转载文章受原作者版权保护。转载请注明原作者出处!