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 ...
随机推荐
- AcWing 278. 数字组合 求方案数目
//M看成背包容量,把每个数看成一个物品,Ai看成是体积 //目标:求总体积恰好为M的方案数目 #include <iostream> using namespace std; ; int ...
- SQL Server查询中特殊字符的处理方法 (SQL Server特殊符号的转义处理)
SQL Server查询中特殊字符的处理方法 (SQL Server特殊符号的转义处理) SQL Server查询中,经常会遇到一些特殊字符,比如单引号'等,这些字符的处理方法,是SQL Server ...
- C语言结构体理解
本质就是数学中集合,里面变量相当于元素,难点在于就是:以前做数学题都是别人给了一个集合,算里面的关系,编程不一样的就是,自己定义一个集合.
- 快速ni
代码: while(p>0) (mul(a,b)) = a*b; { 等同于二分 if(p%2==1) mul(ans,a); 目的是为了二分个基数的二次方乘 ...
- Dimension reduction
materials: 1. Dimension Reduction - IsoMap
- 关于Win32串口
因为近段时间接触Hid相对来说多一些,由此忽略了串口中获取cbInQue这个重要的东西,下面是错误代码 // Win32SerialPortLib.cpp : 定义 DLL 应用程序的导出函数. // ...
- Python 分发包中添加额外文件【新手必学】
在制作一个 Python 分发包时经常需要把一些文件添加到包中.最常见的例子是你希望通过 pip install命令安装 Python 包时会在 /etc/ 等目录下自动添加默认配置文件,由此可以 ...
- Docker - docker images存储位置,引出ls和du命令的不同
docker镜像存储位置 docker info | grep "Docker Root Dir" 例如我的driver是overlay2,则docker镜像的实际存储在/var/ ...
- HDU多校第三场 Hdu6606 Distribution of books 线段树优化DP
Hdu6606 Distribution of books 题意 把一段连续的数字分成k段,不能有空段且段和段之间不能有间隔,但是可以舍去一部分后缀数字,求\(min(max((\sum ai ))\ ...
- AJAX-状态属性
XMLHttpRequest对象的readyState属性 作用:表示xhr对象的请求状态 值:由0到4表示5个状态 0:请求尚未初始化 1:已经打开到WEB服务器的连接,正在向服务器发送请求 2:请 ...