[转载] Controller报错:java.lang.NoSuchMethodException: java.util.List.<init>()

本文介绍了当使用List作为方法参数时可能出现的NoSuchMethodException错误,并提供了两种解决方案:一是通过@RequestParam注解来传递参数;二是将参数封装成一个单独的对象。

参考链接: Java8中的java.util.StringJoiner

报错详情: 

java.lang.NoSuchMethodException: java.util.List.<init>() 以及 No primary or default constructor found for interface java.util.List 

示例: 

/**

* 此接口会产生以上的报错

*/

@GetMapping("sample")

public void sample(List<Integer> ids){

    ...

}

 

报错提示如下: 

java.lang.NoSuchMethodException: java.util.List.<init>()

    at java.lang.Class.getConstructor0(Class.java:3082) ~[na:na]

    at java.lang.Class.getDeclaredConstructor(Class.java:2178) ~[na:na]

    ...

 

报错原因: 对象在初始化时没有找到对应的构造方法,从而导致对象初始化失败。 

解决方法: 提供相应的构造方法即可,如示例接口,有两种处理方法。 方法一,参数前加@RequestParam: 

@GetMapping("sample")

public void sample(@RequestParam List<Integer> ids){

    ...

}

 

方法二,参数封装到对象中: 

@GetMapping("sample")

public void sample(Sample sample){

    List<Integer> ids = sample.getIds();

    ...

}

 

private static class Sample{

    private List<Integer> ids;

    ...

    // getter setter...    

}

解释代码:// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package org.slf4j; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import org.slf4j.event.SubstituteLoggingEvent; import org.slf4j.helpers.NOP_FallbackServiceProvider; import org.slf4j.helpers.Reporter; import org.slf4j.helpers.SubstituteLogger; import org.slf4j.helpers.SubstituteServiceProvider; import org.slf4j.helpers.Util; import org.slf4j.spi.SLF4JServiceProvider; public final class LoggerFactory { static final String CODES_PREFIX = "https://www.slf4j.org/codes.html"; static final String NO_PROVIDERS_URL = "https://www.slf4j.org/codes.html#noProviders"; static final String IGNORED_BINDINGS_URL = "https://www.slf4j.org/codes.html#ignoredBindings"; static final String MULTIPLE_BINDINGS_URL = "https://www.slf4j.org/codes.html#multiple_bindings"; static final String VERSION_MISMATCH = "https://www.slf4j.org/codes.html#version_mismatch"; static final String SUBSTITUTE_LOGGER_URL = "https://www.slf4j.org/codes.html#substituteLogger"; static final String LOGGER_NAME_MISMATCH_URL = "https://www.slf4j.org/codes.html#loggerNameMismatch"; static final String REPLAY_URL = "https://www.slf4j.org/codes.html#replay"; static final String UNSUCCESSFUL_INIT_URL = "https://www.slf4j.org/codes.html#unsuccessfulInit"; static final String UNSUCCESSFUL_INIT_MSG = "org.slf4j.LoggerFactory in failed state. Original exception was thrown EARLIER. See also https://www.slf4j.org/codes.html#unsuccessfulInit"; public static final String PROVIDER_PROPERTY_KEY = "slf4j.provider"; static final int UNINITIALIZED = 0; static final int ONGOING_INITIALIZATION = 1; static final int FAILED_INITIALIZATION = 2; static final int SUCCESSFUL_INITIALIZATION = 3; static final int NOP_FALLBACK_INITIALIZATION = 4; static volatile int INITIALIZATION_STATE = 0; static final SubstituteServiceProvider SUBST_PROVIDER = new SubstituteServiceProvider(); static final NOP_FallbackServiceProvider NOP_FALLBACK_SERVICE_PROVIDER = new NOP_FallbackServiceProvider(); static final String DETECT_LOGGER_NAME_MISMATCH_PROPERTY = "slf4j.detectLoggerNameMismatch"; static final String JAVA_VENDOR_PROPERTY = "java.vendor.url"; static boolean DETECT_LOGGER_NAME_MISMATCH = Util.safeGetBooleanSystemProperty("slf4j.detectLoggerNameMismatch"); static volatile SLF4JServiceProvider PROVIDER; private static final String[] API_COMPATIBILITY_LIST = new String[]{"2.0"}; private static final String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class"; static List<SLF4JServiceProvider> findServiceProviders() { List<SLF4JServiceProvider> providerList = new ArrayList(); ClassLoader classLoaderOfLoggerFactory = LoggerFactory.class.getClassLoader(); SLF4JServiceProvider explicitProvider = loadExplicitlySpecified(classLoaderOfLoggerFactory); if (explicitProvider != null) { providerList.add(explicitProvider); return providerList; } else { ServiceLoader<SLF4JServiceProvider> serviceLoader = getServiceLoader(classLoaderOfLoggerFactory); Iterator<SLF4JServiceProvider> iterator = serviceLoader.iterator(); while(iterator.hasNext()) { safelyInstantiate(providerList, iterator); } return providerList; } } private static ServiceLoader<SLF4JServiceProvider> getServiceLoader(ClassLoader classLoaderOfLoggerFactory) { SecurityManager securityManager = System.getSecurityManager(); ServiceLoader serviceLoader; if (securityManager == null) { serviceLoader = ServiceLoader.load(SLF4JServiceProvider.class, classLoaderOfLoggerFactory); } else { PrivilegedAction<ServiceLoader<SLF4JServiceProvider>> action = () -> { return ServiceLoader.load(SLF4JServiceProvider.class, classLoaderOfLoggerFactory); }; serviceLoader = (ServiceLoader)AccessController.doPrivileged(action); } return serviceLoader; } private static void safelyInstantiate(List<SLF4JServiceProvider> providerList, Iterator<SLF4JServiceProvider> iterator) { try { SLF4JServiceProvider provider = (SLF4JServiceProvider)iterator.next(); providerList.add(provider); } catch (ServiceConfigurationError var3) { ServiceConfigurationError e = var3; Reporter.error("A service provider failed to instantiate:\n" + e.getMessage()); } } private LoggerFactory() { } static void reset() { INITIALIZATION_STATE = 0; } private static final void performInitialization() { bind(); if (INITIALIZATION_STATE == 3) { versionSanityCheck(); } } private static final void bind() { try { List<SLF4JServiceProvider> providersList = findServiceProviders(); reportMultipleBindingAmbiguity(providersList); if (providersList != null && !providersList.isEmpty()) { PROVIDER = (SLF4JServiceProvider)providersList.get(0); PROVIDER.initialize(); INITIALIZATION_STATE = 3; reportActualBinding(providersList); } else { INITIALIZATION_STATE = 4; Reporter.warn("No SLF4J providers were found."); Reporter.warn("Defaulting to no-operation (NOP) logger implementation"); Reporter.warn("See https://www.slf4j.org/codes.html#noProviders for further details."); Set<URL> staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet(); reportIgnoredStaticLoggerBinders(staticLoggerBinderPathSet); } postBindCleanUp(); } catch (Exception var2) { Exception e = var2; failedBinding(e); throw new IllegalStateException("Unexpected initialization failure", e); } } static SLF4JServiceProvider loadExplicitlySpecified(ClassLoader classLoader) { String explicitlySpecified = System.getProperty("slf4j.provider"); if (null != explicitlySpecified && !explicitlySpecified.isEmpty()) { String message; try { String message = String.format("Attempting to load provider \"%s\" specified via \"%s\" system property", explicitlySpecified, "slf4j.provider"); Reporter.info(message); Class<?> clazz = classLoader.loadClass(explicitlySpecified); Constructor<?> constructor = clazz.getConstructor(); Object provider = constructor.newInstance(); return (SLF4JServiceProvider)provider; } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException | ClassNotFoundException var6) { ReflectiveOperationException e = var6; message = String.format("Failed to instantiate the specified SLF4JServiceProvider (%s)", explicitlySpecified); Reporter.error(message, e); return null; } catch (ClassCastException var7) { ClassCastException e = var7; message = String.format("Specified SLF4JServiceProvider (%s) does not implement SLF4JServiceProvider interface", explicitlySpecified); Reporter.error(message, e); return null; } } else { return null; } } private static void reportIgnoredStaticLoggerBinders(Set<URL> staticLoggerBinderPathSet) { if (!staticLoggerBinderPathSet.isEmpty()) { Reporter.warn("Class path contains SLF4J bindings targeting slf4j-api versions 1.7.x or earlier."); Iterator var1 = staticLoggerBinderPathSet.iterator(); while(var1.hasNext()) { URL path = (URL)var1.next(); Reporter.warn("Ignoring binding found at [" + path + "]"); } Reporter.warn("See https://www.slf4j.org/codes.html#ignoredBindings for an explanation."); } } static Set<URL> findPossibleStaticLoggerBinderPathSet() { Set<URL> staticLoggerBinderPathSet = new LinkedHashSet(); try { ClassLoader loggerFactoryClassLoader = LoggerFactory.class.getClassLoader(); Enumeration paths; if (loggerFactoryClassLoader == null) { paths = ClassLoader.getSystemResources("org/slf4j/impl/StaticLoggerBinder.class"); } else { paths = loggerFactoryClassLoader.getResources("org/slf4j/impl/StaticLoggerBinder.class"); } while(paths.hasMoreElements()) { URL path = (URL)paths.nextElement(); staticLoggerBinderPathSet.add(path); } } catch (IOException var4) { IOException ioe = var4; Reporter.error("Error getting resources from path", ioe); } return staticLoggerBinderPathSet; } private static void postBindCleanUp() { fixSubstituteLoggers(); replayEvents(); SUBST_PROVIDER.getSubstituteLoggerFactory().clear(); } private static void fixSubstituteLoggers() { synchronized(SUBST_PROVIDER) { SUBST_PROVIDER.getSubstituteLoggerFactory().postInitialization(); Iterator var1 = SUBST_PROVIDER.getSubstituteLoggerFactory().getLoggers().iterator(); while(var1.hasNext()) { SubstituteLogger substLogger = (SubstituteLogger)var1.next(); Logger logger = getLogger(substLogger.getName()); substLogger.setDelegate(logger); } } } static void failedBinding(Throwable t) { INITIALIZATION_STATE = 2; Reporter.error("Failed to instantiate SLF4J LoggerFactory", t); } private static void replayEvents() { LinkedBlockingQueue<SubstituteLoggingEvent> queue = SUBST_PROVIDER.getSubstituteLoggerFactory().getEventQueue(); int queueSize = queue.size(); int count = 0; int maxDrain = true; List<SubstituteLoggingEvent> eventList = new ArrayList(128); while(true) { int numDrained = queue.drainTo(eventList, 128); if (numDrained == 0) { return; } Iterator var6 = eventList.iterator(); while(var6.hasNext()) { SubstituteLoggingEvent event = (SubstituteLoggingEvent)var6.next(); replaySingleEvent(event); if (count++ == 0) { emitReplayOrSubstituionWarning(event, queueSize); } } eventList.clear(); } } private static void emitReplayOrSubstituionWarning(SubstituteLoggingEvent event, int queueSize) { if (event.getLogger().isDelegateEventAware()) { emitReplayWarning(queueSize); } else if (!event.getLogger().isDelegateNOP()) { emitSubstitutionWarning(); } } private static void replaySingleEvent(SubstituteLoggingEvent event) { if (event != null) { SubstituteLogger substLogger = event.getLogger(); String loggerName = substLogger.getName(); if (substLogger.isDelegateNull()) { throw new IllegalStateException("Delegate logger cannot be null at this state."); } else { if (!substLogger.isDelegateNOP()) { if (substLogger.isDelegateEventAware()) { if (substLogger.isEnabledForLevel(event.getLevel())) { substLogger.log(event); } } else { Reporter.warn(loggerName); } } } } } private static void emitSubstitutionWarning() { Reporter.warn("The following set of substitute loggers may have been accessed"); Reporter.warn("during the initialization phase. Logging calls during this"); Reporter.warn("phase were not honored. However, subsequent logging calls to these"); Reporter.warn("loggers will work as normally expected."); Reporter.warn("See also https://www.slf4j.org/codes.html#substituteLogger"); } private static void emitReplayWarning(int eventCount) { Reporter.warn("A number (" + eventCount + ") of logging calls during the initialization phase have been intercepted and are"); Reporter.warn("now being replayed. These are subject to the filtering rules of the underlying logging system."); Reporter.warn("See also https://www.slf4j.org/codes.html#replay"); } private static final void versionSanityCheck() { try { String requested = PROVIDER.getRequestedApiVersion(); boolean match = false; String[] var2 = API_COMPATIBILITY_LIST; int var3 = var2.length; for(int var4 = 0; var4 < var3; ++var4) { String aAPI_COMPATIBILITY_LIST = var2[var4]; if (requested.startsWith(aAPI_COMPATIBILITY_LIST)) { match = true; } } if (!match) { Reporter.warn("The requested version " + requested + " by your slf4j provider is not compatible with " + Arrays.asList(API_COMPATIBILITY_LIST).toString()); Reporter.warn("See https://www.slf4j.org/codes.html#version_mismatch for further details."); } } catch (Throwable var6) { Throwable e = var6; Reporter.error("Unexpected problem occurred during version sanity check", e); } } private static boolean isAmbiguousProviderList(List<SLF4JServiceProvider> providerList) { return providerList.size() > 1; } private static void reportMultipleBindingAmbiguity(List<SLF4JServiceProvider> providerList) { if (isAmbiguousProviderList(providerList)) { Reporter.warn("Class path contains multiple SLF4J providers."); Iterator var1 = providerList.iterator(); while(var1.hasNext()) { SLF4JServiceProvider provider = (SLF4JServiceProvider)var1.next(); Reporter.warn("Found provider [" + provider + "]"); } Reporter.warn("See https://www.slf4j.org/codes.html#multiple_bindings for an explanation."); } } private static void reportActualBinding(List<SLF4JServiceProvider> providerList) { if (!providerList.isEmpty() && isAmbiguousProviderList(providerList)) { Reporter.info("Actual provider is of type [" + providerList.get(0) + "]"); } } public static Logger getLogger(String name) { ILoggerFactory iLoggerFactory = getILoggerFactory(); return iLoggerFactory.getLogger(name); } public static Logger getLogger(Class<?> clazz) { Logger logger = getLogger(clazz.getName()); if (DETECT_LOGGER_NAME_MISMATCH) { Class<?> autoComputedCallingClass = Util.getCallingClass(); if (autoComputedCallingClass != null && nonMatchingClasses(clazz, autoComputedCallingClass)) { Reporter.warn(String.format("Detected logger name mismatch. Given name: \"%s\"; computed name: \"%s\".", logger.getName(), autoComputedCallingClass.getName())); Reporter.warn("See https://www.slf4j.org/codes.html#loggerNameMismatch for an explanation"); } } return logger; } private static boolean nonMatchingClasses(Class<?> clazz, Class<?> autoComputedCallingClass) { return !autoComputedCallingClass.isAssignableFrom(clazz); } public static ILoggerFactory getILoggerFactory() { return getProvider().getLoggerFactory(); } static SLF4JServiceProvider getProvider() { if (INITIALIZATION_STATE == 0) { Class var0 = LoggerFactory.class; synchronized(LoggerFactory.class) { if (INITIALIZATION_STATE == 0) { INITIALIZATION_STATE = 1; performInitialization(); } } } switch (INITIALIZATION_STATE) { case 1: return SUBST_PROVIDER; case 2: throw new IllegalStateException("org.slf4j.LoggerFactory in failed state. Original exception was thrown EARLIER. See also https://www.slf4j.org/codes.html#unsuccessfulInit"); case 3: return PROVIDER; case 4: return NOP_FALLBACK_SERVICE_PROVIDER; default: throw new IllegalStateException("Unreachable code"); } } }
最新发布
10-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值