Java 反射获取单例实例对象

try {

String className ="className";

    Class clazz = SpringUtil.getBean(className).getClass();

    Method method = clazz.getDeclaredMethod("methodName",Class  params...);

//每次从Spring容器中获取实例对象,不要使用clazz.newInstance(),就可以保证每次获取的对象是同一个实例对象

    return method.invoke(SpringUtil.getBean(className), params...);

}catch (NoSuchMethodException e) {

log.info("获取指定方式失败:{}", e.getMessage());

}catch (IllegalAccessException e) {

log.info("反射调用方法参数错误:{}", e.getMessage());

}catch (InvocationTargetException e) {

log.info("反射调用方法InvocationTargetException错误:{}", e);

}


SpringBoot生产实例对象名称的规则:

/**

* SpringBoot  bean的命名规则

*

* @param name

* @return

*/

public static Stringdecapitalize(String name) {

if (name ==null || name.length() ==0) {

return name;

    }

if (name.length() >1 && Character.isUpperCase(name.charAt(1)) &&

Character.isUpperCase(name.charAt(0))) {

return name;

    }

char chars[] = name.toCharArray();

    chars[0] = Character.toLowerCase(chars[0]);

    return new String(chars);

}

你可能感兴趣的:(Java 反射获取单例实例对象)