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反射--超级好用的方法的更多相关文章

  1. Java 反射 调用私有域和方法(setAccessible)

    Java 反射 调用私有域和方法(setAccessible) @author ixenos AccessibleObject类 Method.Field和Constructor类共同继承了Acces ...

  2. 【译】7. Java反射——私有字段和私有方法

    原文地址:http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html =================== ...

  3. Java反射理解(五)-- 方法反射的基本操作

    Java反射理解(五)-- 方法反射的基本操作 方法的反射 1. 如何获取某个方法 方法的名称和方法的参数列表才能唯一决定某个方法 2. 方法反射的操作 method.invoke(对象,参数列表) ...

  4. Java反射机制调用对象的方法 —— 将一个对象的属性值赋值给另一个对象的属性

    模拟一个场景: 众所周知,EasyExcel导出Excel文档是依赖于注解完成的,在实体类需要导出的属性上面加上注解,导出的时候会自动识别该属性. 假如我们现在需要导出用户的信息,又不想污染原本的实体 ...

  5. 深入分析Java反射(一)-核心类库和方法

    前提 Java反射的API在JavaSE1.7的时候已经基本完善,但是本文编写的时候使用的是Oracle JDK11,因为JDK11对于sun包下的源码也上传了,可以直接通过IDE查看对应的源码和进行 ...

  6. java反射调用某个对象的方法

    // 反射调用某个对象的方法 public Object invokeMethod(Object methodObject, String methodName, Object[] args) thr ...

  7. Java反射《四》获取方法

    package com.study.reflect; import java.lang.reflect.InvocationTargetException; import java.lang.refl ...

  8. 有关java反射的几个小方法的作用和区别

    1.Class类中 getXXX()和getDeclaredXXX()的作用和区别: 前者获取某个类的所有公共(public)的字段(or方法or构造函数),包括父类.后者获取所有的字段(or方法or ...

  9. 第五课 JAVA反射获取对象属性和方法(通过配置文件)

    Service1.java package reflection; public class Service1 { public void doService1(){ System.out.print ...

随机推荐

  1. Java修饰符类型

    转自原文:http://www.yiibai.com/java/java_modifier_types.html 修饰符是添加到这些定义来改变它们的含义的关键词. Java语言有各种各样修饰词,其中包 ...

  2. Wannafly Camp 2020 Day 2C 纳新一百的石子游戏

    为什么为了这么个简单题发博客呢? 因为我又因为位运算运算符优先级的问题血了 #include <bits/stdc++.h> using namespace std; #define in ...

  3. 一些好用的Jquery插件

    1.jquery.resizableColumns.min.js,可以给table列加上调节宽度的功能 2.Jquery.cookie.js,可以在客户端写入和获取cookie 3.Paginatio ...

  4. Linux平台下C++使用JsonCPP解析Json字符串

    JsonCPP安装 安装 scons 下载地址: http://sourceforge.net/projects/scons/files/scons/2.1.0/scons-2.1.0.tar.gz/ ...

  5. Java.util.Calendar类

    Java.util.Calendar类 package myProject; import java.text.SimpleDateFormat; import java.util.Calendar; ...

  6. 第四十六篇 入门机器学习——kNN - k近邻算法(k-Nearest Neighbors)

    No.1. k-近邻算法的特点 No.2. 准备工作,导入类库,准备测试数据 No.3. 构建训练集 No.4. 简单查看一下训练数据集大概是什么样子,借助散点图 No.5. kNN算法的目的是,假如 ...

  7. AcWing 282. 石子合并

    #include <iostream> #include <algorithm> using namespace std; ; int n; int s[N];//前缀和 in ...

  8. C语言 fputs

    C语言 fputs #include <stdio.h> int fputs(const char * str, FILE * stream); 功能:将str所指定的字符串写入到stre ...

  9. 事务:Transaction详解

    1.事务概念: 一组sql语句操作单元,组内所有SQL语句完成一个业务,如果整组成功:意味着全部SQL都实现:如果其中任何一个失败,意味着整个操作都失败.失败,意味着整个过程都是没有意义的.应该是数据 ...

  10. mysql和oracle建表语句以及数据类型的区别

    1.mysql和oracle建表语句的区别 mysql DROP TABLE IF EXISTS `order`;CREATE TABLE `order` (  `id` int(11) NOT NU ...