java反射--超级好用的方法
1.根据方法名,获取类的对应的方法
Method changeSessionIdMethod = ReflectionUtils.findMethod(HttpServletRequest.class, "changeSessionId");
if(changeSessionIdMethod == null) {
throw new IllegalStateException("HttpServletRequest.changeSessionId is undefined. Are you using a Servlet 3.1+ environment?");
}
System.out.println(changeSessionIdMethod);
2.休眠当前线程
TimeUnit.MILLISECONDS.sleep(1000);
3. 替换配置文件中特殊的变量将变量中含有 @{test.test} 将变量 test.test 替换为系统中的其他值。
private static final PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("@{", "}", ":", false);
private static final PlaceholderResolver placeholderResolver=new PlaceholderResolver(){
@Override
public String resolvePlaceholder(String key) {
return System.getProperty(key);
}
};
4.获取对象的方法名称。dubbo 获取dubbo接口里的方法
String[] methods = Wrapper.getWrapper(interfaceClass).getMethodNames();
5. {0} 字符串格式化。
String template="test1={0},test2={1},test3={2}";
Object[] objects=new Object[]{0,1,"test2"};
String emailContent = MessageFormat.format(template, objects);
System.out.println(emailContent);
6.spring HiddenHttpMethodFilter 将http里post方法转化为参数里的方法
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException { HttpServletRequest requestToUse = request; if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
String paramValue = request.getParameter(this.methodParam);
if (StringUtils.hasLength(paramValue)) {
requestToUse = new HttpMethodRequestWrapper(request, paramValue);
}
} filterChain.doFilter(requestToUse, response);
}
7.判断classpath 中是否存在某个类 原理:先判断是否是基础类型, 再 根据 ClassLoader clToUse = classLoader; (clToUse != null ? clToUse.loadClass(name) : Class.forName(name))
org.springframework.util.ClassUtils
if (ClassUtils.isPresent(REACTIVE_WEB_ENVIRONMENT_CLASS, null)
&& !ClassUtils.isPresent(MVC_WEB_ENVIRONMENT_CLASS, null)) {
return WebApplicationType.REACTIVE;
}
for (String className : WEB_ENVIRONMENT_CLASSES) {
if (!ClassUtils.isPresent(className, null)) {
return WebApplicationType.NONE;
}
}
9.获取classpath下的文件,和 jar包里的文件。
public static void main(String[] args) throws Exception {
Enumeration<URL> urls = ClassLoader.getSystemResources("META-INF/services/ch.qos.logback.classic.spi.Configurator");
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
System.out.println(url.getPath());
}
}
// 从url 读取文件内容
BufferedReader reader = new BufferedReader(new InputStreamReader(resourceURL.openStream(), "utf-8"));
10.向目录里写文件,目录和文件不能直接用字符串链接,如目录为:.,文件名为:test.log,直接链接为.log会出错。
public class FileUtil {
public static File getFile(String path,String fileName) throws IOException{
File directory=new File(path);
String filePath=directory.getCanonicalPath();
return new File(filePath+"/"+fileName);
}
}
11.字符串按字节长度截取
public static byte[] subBytes(byte[] src, int begin, int count) {
byte[] bs = new byte[count];
System.arraycopy(src, begin, bs, 0, count);
return bs;
}
if (!StringUtil.isNullOrEmpty(po.getContent())){
byte[] contentB= new byte[0];
try {
contentB = po.getContent().getBytes("utf-8");
if (contentB.length>1024){
po.setContent(new String(StringUtil.subBytes(contentB,0,1024),"utf-8"));
}
} catch (UnsupportedEncodingException e) {
String result="content bytes length > 1024,convert error";
po.setContent(result);
log.error(result,e);
}
}
12.获取类的调用链路
private Class<?> deduceMainApplicationClass() {
try {
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
if ("main".equals(stackTraceElement.getMethodName())) {
return Class.forName(stackTraceElement.getClassName());
}
}
}
catch (ClassNotFoundException ex) {
// Swallow and continue
}
return null;
}
java反射--超级好用的方法的更多相关文章
- Java 反射 调用私有域和方法(setAccessible)
Java 反射 调用私有域和方法(setAccessible) @author ixenos AccessibleObject类 Method.Field和Constructor类共同继承了Acces ...
- 【译】7. Java反射——私有字段和私有方法
原文地址:http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html =================== ...
- Java反射理解(五)-- 方法反射的基本操作
Java反射理解(五)-- 方法反射的基本操作 方法的反射 1. 如何获取某个方法 方法的名称和方法的参数列表才能唯一决定某个方法 2. 方法反射的操作 method.invoke(对象,参数列表) ...
- Java反射机制调用对象的方法 —— 将一个对象的属性值赋值给另一个对象的属性
模拟一个场景: 众所周知,EasyExcel导出Excel文档是依赖于注解完成的,在实体类需要导出的属性上面加上注解,导出的时候会自动识别该属性. 假如我们现在需要导出用户的信息,又不想污染原本的实体 ...
- 深入分析Java反射(一)-核心类库和方法
前提 Java反射的API在JavaSE1.7的时候已经基本完善,但是本文编写的时候使用的是Oracle JDK11,因为JDK11对于sun包下的源码也上传了,可以直接通过IDE查看对应的源码和进行 ...
- java反射调用某个对象的方法
// 反射调用某个对象的方法 public Object invokeMethod(Object methodObject, String methodName, Object[] args) thr ...
- Java反射《四》获取方法
package com.study.reflect; import java.lang.reflect.InvocationTargetException; import java.lang.refl ...
- 有关java反射的几个小方法的作用和区别
1.Class类中 getXXX()和getDeclaredXXX()的作用和区别: 前者获取某个类的所有公共(public)的字段(or方法or构造函数),包括父类.后者获取所有的字段(or方法or ...
- 第五课 JAVA反射获取对象属性和方法(通过配置文件)
Service1.java package reflection; public class Service1 { public void doService1(){ System.out.print ...
随机推荐
- adb server version (xx) doesn't match this client (xx); killing...
问题 查看AndroidSDK的adb版本 查看模拟器adb的版本号 安装路径/bin目录下的 nox_adb.exe 将AndroidSDK的adb复制出来,重命名为nox_adb.exe,覆盖模拟 ...
- 02 Django虚拟环境搭建
01 创建虚拟环境目录 该目录用于存放所有虚拟环境. cd / mkdir venv cd venv 02 创建当前项目的虚拟环境 virtualenv --python=/usr/bin/pytho ...
- 跨站点请求伪造(CSRF、XSRF)
相关文章: 1. http://www.cnblogs.com/xiaoqian1993/p/5816085.html 深入解析跨站请求伪造漏洞:原理剖析 2 .http://blog.csdn.n ...
- 【Python】字符串的格式化
一一对应 符号要用英文半角形式
- Android 开发OOM解决方案
OOM(Out Of Memory)在加载图片过多或者过大的情况下会发生OOM,可以查看APP最高可用内存: int maxMemory = (int) (Runtim.getRuntime().ma ...
- ISCC2018_leftleftrightright-Writeup
leftleftrightright(150) 这个题学到了不少东西,值得认真写一下 下载好文件后发现是upx的壳,upx -d直接脱掉后运行,发现是经典的check输入的题目(作为一个linuxer ...
- h264 RTP STAP-A单时间聚合包
参考官方文档:http://www.rosoo.net/Files/UpFiles/RsProduct/avtools/2009-4/2009491562537854.txt 聚合包的RTP荷载格式的 ...
- 220. 存在重复元素 III
题目: 给定一个整数数组,判断数组中是否有两个不同的索引 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值最大为 t,并且 i 和 j 之间的差的绝对值最大为 ķ. 示例 1: ...
- Dapper简介
Dapper文档 一,介绍:Dapper是一款轻量级ORM工具.如果你在小的项目中,使用Entity Framework.NHibernate 来处理大数据访问及关系映射,未免有点杀鸡用牛刀.你又觉得 ...
- Maven设置阿里云镜像
<mirrors> <mirror> <id>alimaven</id> <name>aliyun maven</name> & ...