本文已参与「新人创作礼」活动,一起开启掘金创作之路。
java运行时异常和抛出异常的区别
与张航日常交流的心得,
当在写事务回滚的时候,
我们会利用异常来执行是否提交和回滚。
异常分为运行时异常与受查异常。
运行时异常,是 RuntimeException 类或其子类,即只有在运行时才出现的异常。如,
NullPointerException、ArrayIndexOutOfBoundsException、IllegalArgumentException 等均属于
运行时异常。这些异常由 JVM 抛出,在编译时不要求必须处理(捕获或抛出)。但,只要代
码编写足够仔细,程序足够健壮,运行时异常是可以避免的。
受查异常,也叫编译时异常,即在代码编写时要求必须捕获或抛出的异常,若不处理,
则无法通过编译。如 SQLException,ClassNotFoundException,IOException 等都属于受查异常。
RuntimeException 及其子类以外的异常,均属于受查异常。当然,用户自定义的 Exception
的子类,即用户自定义的异常也属受查异常。程序员在定义异常时,只要未明确声明定义的
为 RuntimeException 的子类,那么定义的就是受查异常。
学习java第150天,使用反射+动态代理+爆破 实现动态更改注解
话不多说篇-直接干代码
// 根据运行环境设置表名
String tableName = "execution(* *..SomeServiceImpl.doThird(..))";
// 获取 MyAspect 上的 Pointcut 注解
Pointcut annoPoincut = MyAspect.class.getMethod("myPointCut").getAnnotation(Pointcut.class);
//获取 MyAspect 上的 Aspect 注解
Aspect annoAspect = MyAspect.class.getAnnotation(Aspect.class);
//判断是否为空
if (annoPoincut == null) {
throw new RuntimeException("please add @Table for Test");
}
// 获取代理处理器
InvocationHandler invocationHandler = Proxy.getInvocationHandler(annoPoincut);
// 过去私有 memberValues 属性
Field f = invocationHandler.getClass().getDeclaredField("memberValues");
//设置方法或类为可访问
f.setAccessible(true);
// 获取实例的属性map
Map<String, Object> memberValues = (Map<String, Object>) f.get(invocationHandler);
//输出注解
memberValues.forEach( (s, o) -> System.out.println(s + "\t" +o +"\n"));
// 修改属性值 随意修改属性值
memberValues.put("value",tableName);
导包
import com.li.bao08.MyAspect;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Map;