class.newInstance is deprecated #2435 (#2437)

* Class.newInstance() is deprecated in Java 9+ #2435

Signed-off-by: olivier lamy <oliver.lamy@gmail.com>
This commit is contained in:
Olivier Lamy 2018-04-17 19:07:20 +10:00 committed by GitHub
parent 882deb00b4
commit f36eba4577
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
45 changed files with 91 additions and 100 deletions

View File

@ -47,7 +47,7 @@ public class JettyRunTask extends Task
private File tempDirectory;
/** List of web applications to be deployed. */
private List<AntWebAppContext> webapps = new ArrayList<AntWebAppContext>();
private List<AntWebAppContext> webapps = new ArrayList<>();
/** Location of jetty.xml file. */
private File jettyXml;
@ -147,20 +147,17 @@ public class JettyRunTask extends Task
{
try
{
this.requestLog = (RequestLog) Class.forName(className).newInstance();
}
catch (InstantiationException e)
{
throw new BuildException("Request logger instantiation exception: " + e);
}
catch (IllegalAccessException e)
{
throw new BuildException("Request logger instantiation exception: " + e);
this.requestLog = (RequestLog) Class.forName(className).getDeclaredConstructor().newInstance();
}
catch (ClassNotFoundException e)
{
throw new BuildException("Unknown request logger class: " + className);
}
catch (Exception e)
{
throw new BuildException("Request logger instantiation exception: " + e);
}
}
public String getRequestLog()

View File

@ -206,7 +206,7 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService
}
else if (callback instanceof PasswordCallback)
{
((PasswordCallback)callback).setPassword((char[]) credentials.toString().toCharArray());
((PasswordCallback)callback).setPassword(credentials.toString().toCharArray());
}
else if (callback instanceof ObjectCallback)
{
@ -227,7 +227,7 @@ public class JAASLoginService extends AbstractLifeCycle implements LoginService
else
{
Class<?> clazz = Loader.loadClass(_callbackHandlerClass);
callbackHandler = (CallbackHandler)clazz.newInstance();
callbackHandler = (CallbackHandler)clazz.getDeclaredConstructor().newInstance();
}
//set up the login context
//TODO jaspi requires we provide the Configuration parameter

View File

@ -105,17 +105,9 @@ public class JDBCLoginModule extends AbstractDatabaseLoginModule
dbPassword = "";
if (dbDriver != null)
Loader.loadClass(dbDriver).newInstance();
Loader.loadClass(dbDriver).getDeclaredConstructor().newInstance();
}
catch (ClassNotFoundException e)
{
throw new IllegalStateException (e.toString());
}
catch (InstantiationException e)
{
throw new IllegalStateException (e.toString());
}
catch (IllegalAccessException e)
catch (Exception e)
{
throw new IllegalStateException (e.toString());
}

View File

@ -148,7 +148,7 @@ public class ObjectMBean implements DynamicMBean
LOG.ignore(e);
if (ModelMBean.class.isAssignableFrom(mClass))
{
mbean = mClass.newInstance();
mbean = mClass.getDeclaredConstructor().newInstance();
((ModelMBean)mbean).setManagedResource(o, "objectReference");
}
}

View File

@ -187,7 +187,9 @@ public class ContextFactory implements ObjectFactory
Reference ref = (Reference)obj;
StringRefAddr parserAddr = (StringRefAddr)ref.get("parser");
String parserClassName = (parserAddr==null?null:(String)parserAddr.getContent());
NameParser parser = (NameParser)(parserClassName==null?null:loader.loadClass(parserClassName).newInstance());
NameParser parser =
(NameParser)(parserClassName==null?
null:loader.loadClass(parserClassName).getDeclaredConstructor().newInstance());
return new NamingContext (env,
name.get(0),

View File

@ -182,7 +182,8 @@ public class ContainerTldBundleDiscoverer implements TldBundleDiscoverer
// Class.getForName("org.apache.jasper.runtime.JspFactoryImpl")
// however its bundles does not import the jasper package
// so it fails. let's help things out:
fact = (JspFactory) JettyBootstrapActivator.class.getClassLoader().loadClass(DEFAULT_JSP_FACTORY_IMPL_CLASS).newInstance();
fact = (JspFactory) JettyBootstrapActivator.class.getClassLoader()
.loadClass(DEFAULT_JSP_FACTORY_IMPL_CLASS).getDeclaredConstructor().newInstance();
JspFactory.setDefaultFactory(fact);
}
}

View File

@ -93,7 +93,8 @@ public class JSTLBundleDiscoverer implements TldBundleDiscoverer
// Class.getForName("org.apache.jasper.runtime.JspFactoryImpl")
// however its bundles does not import the jasper package
// so it fails. let's help things out:
fact = (JspFactory) JettyBootstrapActivator.class.getClassLoader().loadClass(DEFAULT_JSP_FACTORY_IMPL_CLASS).newInstance();
fact = (JspFactory) JettyBootstrapActivator.class.getClassLoader()
.loadClass(DEFAULT_JSP_FACTORY_IMPL_CLASS).getDeclaredConstructor().newInstance();
JspFactory.setDefaultFactory(fact);
}

View File

@ -52,7 +52,8 @@ public class BundleClassLoaderHelperFactory
try
{
//if a fragment has not provided their own impl
helper = (BundleClassLoaderHelper) Class.forName(BundleClassLoaderHelper.CLASS_NAME).newInstance();
helper = (BundleClassLoaderHelper) Class.forName(BundleClassLoaderHelper.CLASS_NAME)
.getDeclaredConstructor().newInstance();
}
catch (Throwable t)
{

View File

@ -45,7 +45,8 @@ public class BundleFileLocatorHelperFactory
try
{
//see if a fragment has supplied an alternative
helper = (BundleFileLocatorHelper) Class.forName(BundleFileLocatorHelper.CLASS_NAME).newInstance();
helper = (BundleFileLocatorHelper) Class.forName(BundleFileLocatorHelper.CLASS_NAME)
.getDeclaredConstructor().newInstance();
}
catch (Throwable t)
{

View File

@ -280,27 +280,11 @@ public class PackageAdminServiceTracker implements ServiceListener
Class<?> c = Class.forName(fragmentActivator);
if (c != null)
{
BundleActivator bActivator = (BundleActivator) c.newInstance();
BundleActivator bActivator = (BundleActivator) c.getDeclaredConstructor().newInstance();
bActivator.start(_context);
_activatedFragments.add(bActivator);
}
}
catch (NullPointerException e)
{
// e.printStackTrace();
}
catch (InstantiationException e)
{
// e.printStackTrace();
}
catch (IllegalAccessException e)
{
// e.printStackTrace();
}
catch (ClassNotFoundException e)
{
// e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();

View File

@ -61,7 +61,7 @@ public class ContainerInitializer
try
{
_target = (ServletContainerInitializer)loader.loadClass(m.group(1)).newInstance();
_target = (ServletContainerInitializer)loader.loadClass(m.group(1)).getDeclaredConstructor().newInstance();
String[] interested = StringUtil.arrayFromString(m.group(2));
_interestedTypes = new Class<?>[interested.length];
for (int i=0;i<interested.length;i++)

View File

@ -85,7 +85,7 @@ public class ProxyServletFailureTest
public ProxyServletFailureTest(Class<?> proxyServletClass) throws Exception
{
this.proxyServlet = (ProxyServlet)proxyServletClass.newInstance();
this.proxyServlet = (ProxyServlet)proxyServletClass.getDeclaredConstructor().newInstance();
}
private void prepareProxy() throws Exception

View File

@ -77,7 +77,7 @@ public class ProxyServletLoadTest
public ProxyServletLoadTest(Class<?> proxyServletClass) throws Exception
{
proxyServlet = (AbstractProxyServlet)proxyServletClass.newInstance();
proxyServlet = (AbstractProxyServlet)proxyServletClass.getDeclaredConstructor().newInstance();
}
private void startServer(HttpServlet servlet) throws Exception

View File

@ -126,7 +126,7 @@ public class ProxyServletTest
public ProxyServletTest(Class<?> proxyServletClass) throws Exception
{
this.proxyServlet = (AbstractProxyServlet)proxyServletClass.newInstance();
this.proxyServlet = (AbstractProxyServlet)proxyServletClass.getDeclaredConstructor().newInstance();
}
private void startServer(HttpServlet servlet) throws Exception

View File

@ -170,7 +170,7 @@ public class JDBCLoginService extends AbstractLoginService
+ " = u."
+ _userRoleTableRoleKey;
Loader.loadClass(_jdbcDriver).newInstance();
Loader.loadClass(_jdbcDriver).getDeclaredConstructor().newInstance();
super.doStart();
}

View File

@ -107,7 +107,7 @@ public class AsyncContextState implements AsyncContext
return contextHandler.getServletContext().createListener(clazz);
try
{
return clazz.newInstance();
return clazz.getDeclaredConstructor().newInstance();
}
catch (Exception e)
{

View File

@ -2532,7 +2532,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
public <T> T createInstance (Class<T> clazz) throws Exception
{
T o = clazz.newInstance();
T o = clazz.getDeclaredConstructor().newInstance();
return o;
}
@ -2829,13 +2829,9 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
{
try
{
return clazz.newInstance();
return clazz.getDeclaredConstructor().newInstance();
}
catch (InstantiationException e)
{
throw new ServletException(e);
}
catch (IllegalAccessException e)
catch (Exception e)
{
throw new ServletException(e);
}

View File

@ -247,7 +247,7 @@ public class ContextHandlerCollection extends HandlerCollection
{
try
{
ContextHandler context = _contextClass.newInstance();
ContextHandler context = _contextClass.getDeclaredConstructor().newInstance();
context.setContextPath(contextPath);
context.setResourceBase(resourceBase);
addHandler(context);

View File

@ -327,7 +327,7 @@ public class RequestLogTest
{
try
{
throw (Throwable)(Class.forName(value).newInstance());
throw (Throwable)(Class.forName(value).getDeclaredConstructor().newInstance());
}
catch(ServletException | IOException | Error | RuntimeException e)
{

View File

@ -120,7 +120,7 @@ public class FilterHolder extends Holder<Filter>
ServletContext context=_servletHandler.getServletContext();
_filter=(context instanceof ServletContextHandler.Context)
?((ServletContextHandler.Context)context).createFilter(getHeldClass())
:getHeldClass().newInstance();
:getHeldClass().getDeclaredConstructor().newInstance();
}
catch (ServletException se)
{

View File

@ -327,7 +327,7 @@ public class ServletContextHandler extends ContextHandler
{
try
{
return (SecurityHandler)_defaultSecurityHandlerClass.newInstance();
return _defaultSecurityHandlerClass.getDeclaredConstructor().newInstance();
}
catch(Exception e)
{

View File

@ -20,6 +20,7 @@ package org.eclipse.jetty.servlet;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
@ -1283,15 +1284,18 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
* @throws ServletException if unable to create a new instance
* @throws IllegalAccessException if not allowed to create a new instance
* @throws InstantiationException if creating new instance resulted in error
* @throws NoSuchMethodException if creating new instance resulted in error
* @throws InvocationTargetException If creating new instance throws an exception
*/
protected Servlet newInstance() throws ServletException, IllegalAccessException, InstantiationException
protected Servlet newInstance() throws ServletException, IllegalAccessException, InstantiationException,
NoSuchMethodException, InvocationTargetException
{
try
{
ServletContext ctx = getServletHandler().getServletContext();
if (ctx instanceof ServletContextHandler.Context)
return ((ServletContextHandler.Context)ctx).createServlet(getHeldClass());
return getHeldClass().newInstance();
return getHeldClass().getDeclaredConstructor().newInstance();
}
catch (ServletException se)
{
@ -1300,6 +1304,10 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
throw (InstantiationException)cause;
if (cause instanceof IllegalAccessException)
throw (IllegalAccessException)cause;
if (cause instanceof NoSuchMethodException)
throw (NoSuchMethodException)cause;
if (cause instanceof InvocationTargetException)
throw (InvocationTargetException)cause;
throw se;
}
}

View File

@ -709,7 +709,7 @@ public class JSON
{
try
{
Convertible conv = (Convertible)type.newInstance();
Convertible conv = (Convertible)type.getDeclaredConstructor().newInstance();
conv.fromJSON(map);
return conv;
}

View File

@ -38,7 +38,8 @@ public class JSONCollectionConvertor implements JSON.Convertor
{
try
{
Collection result = (Collection)Loader.loadClass((String)object.get("class")).newInstance();
Collection result = (Collection)Loader.loadClass((String)object.get("class"))
.getDeclaredConstructor().newInstance();
Collections.addAll(result, (Object[])object.get("list"));
return result;
}

View File

@ -182,7 +182,7 @@ public class JSONPojoConvertor implements JSON.Convertor
Object obj = null;
try
{
obj = _pojoClass.newInstance();
obj = _pojoClass.getDeclaredConstructor().newInstance();
}
catch(Exception e)
{

View File

@ -18,6 +18,7 @@
package org.eclipse.jetty.util;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
@ -58,13 +59,14 @@ public class DecoratedObjectFactory implements Iterable<Decorator>
this.decorators.clear();
}
public <T> T createInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException
public <T> T createInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException,
NoSuchMethodException, InvocationTargetException
{
if (LOG.isDebugEnabled())
{
LOG.debug("Creating Instance: " + clazz);
}
T o = clazz.newInstance();
T o = clazz.getDeclaredConstructor().newInstance();
return decorate(o);
}

View File

@ -77,8 +77,8 @@ public class IncludeExcludeSet<T,P> implements Predicate<P>
{
try
{
_includes = setClass.newInstance();
_excludes = setClass.newInstance();
_includes = setClass.getDeclaredConstructor().newInstance();
_excludes = setClass.getDeclaredConstructor().newInstance();
if(_includes instanceof Predicate)
{
@ -98,7 +98,11 @@ public class IncludeExcludeSet<T,P> implements Predicate<P>
_excludePredicate = new SetContainsPredicate(_excludes);
}
}
catch (InstantiationException | IllegalAccessException e)
catch (RuntimeException e)
{
throw e;
}
catch (Exception e)
{
throw new RuntimeException(e);
}

View File

@ -175,7 +175,7 @@ public class Log
Class<?> log_class = __logClass==null?null:Loader.loadClass(Log.class,__logClass);
if (LOG == null || (log_class!=null && !LOG.getClass().equals(log_class)))
{
LOG = (Logger)log_class.newInstance();
LOG = (Logger)log_class.getDeclaredConstructor().newInstance();
if(announce)
{
LOG.debug("Logging to {} via {}", LOG, log_class.getName());

View File

@ -1032,7 +1032,7 @@ public class WebAppContext extends ServletContextHandler implements WebAppClassL
_configurationClasses.addAll(Configuration.ClassList.serverDefault(getServer()));
}
for (String configClass : _configurationClasses)
_configurations.add((Configuration)Loader.loadClass(configClass).newInstance());
_configurations.add((Configuration)Loader.loadClass(configClass).getDeclaredConstructor().newInstance());
}
/* ------------------------------------------------------------ */

View File

@ -61,7 +61,7 @@ public class WebAppClassLoaderUrlStreamTest extends WebAppClassLoaderTest
try
{
Class<?> clazz = Class.forName(className, false, classLoader);
handler = (URLStreamHandler) clazz.newInstance();
handler = (URLStreamHandler) clazz.getDeclaredConstructor().newInstance();
break;
}
catch (Exception ignore)

View File

@ -419,11 +419,11 @@ public class ClientContainer extends ContainerLifeCycle implements WebSocketCont
{
try
{
return newClientEndpointInstance(endpointClass.newInstance(),config);
return newClientEndpointInstance(endpointClass.getDeclaredConstructor().newInstance(),config);
}
catch (InstantiationException | IllegalAccessException e)
catch (Exception e)
{
throw new InvalidWebSocketException("Unable to instantiate websocket: " + endpointClass.getClass());
throw new InvalidWebSocketException("Unable to instantiate websocket: " + endpointClass.getClass(), e);
}
}

View File

@ -194,9 +194,9 @@ public class DecoderFactory implements Configurable
Decoder decoder = containerScope.getObjectFactory().createInstance(decoderClass);
return new Wrapper(decoder,metadata);
}
catch (InstantiationException | IllegalAccessException e)
catch (Exception e)
{
throw new IllegalStateException("Unable to instantiate Decoder: " + decoderClass.getName());
throw new IllegalStateException("Unable to instantiate Decoder: " + decoderClass.getName(), e);
}
}
}

View File

@ -181,9 +181,9 @@ public class EncoderFactory implements Configurable
Encoder encoder = containerScope.getObjectFactory().createInstance(encoderClass);
return new Wrapper(encoder,metadata);
}
catch (InstantiationException | IllegalAccessException e)
catch (Exception e)
{
throw new IllegalStateException("Unable to instantiate Encoder: " + encoderClass.getName());
throw new IllegalStateException("Unable to instantiate Encoder: " + encoderClass.getName(),e);
}
}
}

View File

@ -60,9 +60,9 @@ public class AnnotatedClientEndpointConfig implements ClientEndpointConfig
{
try
{
this.configurator = anno.configurator().newInstance();
this.configurator = anno.configurator().getDeclaredConstructor( ).newInstance();
}
catch (InstantiationException | IllegalAccessException e)
catch (Exception e)
{
StringBuilder err = new StringBuilder();
err.append("Unable to instantiate ClientEndpoint.configurator() of ");

View File

@ -109,7 +109,7 @@ public class OnCloseTest
// Build up EventDriver
WebSocketPolicy policy = WebSocketPolicy.newClientPolicy();
ClientEndpointConfig config = metadata.getConfig();
TrackingSocket endpoint = (TrackingSocket)testcase.closeClass.newInstance();
TrackingSocket endpoint = (TrackingSocket)testcase.closeClass.getDeclaredConstructor().newInstance();
EndpointInstance ei = new EndpointInstance(endpoint,config,metadata);
JsrEvents<ClientEndpoint, ClientEndpointConfig> jsrevents = new JsrEvents<>(metadata);

View File

@ -129,9 +129,9 @@ public class AnnotatedServerEndpointConfig implements ServerEndpointConfig
{
try
{
cfgr = anno.configurator().newInstance();
cfgr = anno.configurator().getDeclaredConstructor( ).newInstance();
}
catch (InstantiationException | IllegalAccessException e)
catch (Exception e)
{
StringBuilder err = new StringBuilder();
err.append("Unable to instantiate ClientEndpoint.configurator() of ");

View File

@ -69,9 +69,9 @@ public final class ContainerDefaultConfigurator extends Configurator
{
// Since this is started via a ServiceLoader, this class has no Scope or context
// that can be used to obtain a ObjectFactory from.
return endpointClass.newInstance();
return endpointClass.getDeclaredConstructor().newInstance();
}
catch (IllegalAccessException e)
catch (Exception e)
{
throw new InstantiationException(String.format("%s: %s",e.getClass().getName(),e.getMessage()));
}

View File

@ -255,7 +255,7 @@ public class WebSocketServerContainerInitializer implements ServletContainerInit
}
try
{
ServerApplicationConfig config = clazz.newInstance();
ServerApplicationConfig config = clazz.getDeclaredConstructor( ).newInstance();
Set<ServerEndpointConfig> seconfigs = config.getEndpointConfigs(discoveredExtendedEndpoints);
if (seconfigs != null)
@ -271,7 +271,7 @@ public class WebSocketServerContainerInitializer implements ServletContainerInit
deployableAnnotatedEndpoints.addAll(annotatedClasses);
}
}
catch (InstantiationException | IllegalAccessException e)
catch (Exception e)
{
throw new ServletException("Unable to instantiate: " + clazz.getName(),e);
}

View File

@ -66,7 +66,7 @@ public class WebSocketExtensionFactory extends ExtensionFactory
}
return ext;
}
catch (InstantiationException | IllegalAccessException e)
catch (Exception e)
{
throw new WebSocketException("Cannot instantiate extension: " + extClass,e);
}

View File

@ -157,9 +157,9 @@ public class NativeWebSocketConfiguration extends ContainerLifeCycle implements
{
try
{
return endpointClass.newInstance();
return endpointClass.getDeclaredConstructor().newInstance();
}
catch (InstantiationException | IllegalAccessException e)
catch (Exception e)
{
throw new WebSocketException("Unable to create instance of " + endpointClass.getName(), e);
}

View File

@ -294,7 +294,7 @@ public class WebSocketServerFactory extends ContainerLifeCycle implements WebSoc
{
return objectFactory.createInstance(firstClass);
}
catch (InstantiationException | IllegalAccessException e)
catch (Exception e)
{
throw new WebSocketException("Unable to create instance of " + firstClass, e);
}

View File

@ -329,7 +329,7 @@ public class HttpInputIntegrationTest
{
System.err.printf("[%d] TEST c=%s, m=%s, delayDispatch=%b delayInFrame=%s content-length:%d expect=%d read=%d content:%s%n",_id,_client.getSimpleName(),_mode,__config.isDelayDispatchUntilContent(),_delay,_length,_status,_read,_send);
TestClient client=_client.newInstance();
TestClient client=_client.getDeclaredConstructor().newInstance();
String response = client.send("/ctx/test?mode="+_mode,50,_delay,_length,_send);
int sum=0;
@ -368,7 +368,7 @@ public class HttpInputIntegrationTest
{
try
{
TestClient client=_client.newInstance();
TestClient client=_client.getDeclaredConstructor().newInstance();
for (int j=0;j<loops;j++)
{
String response = client.send("/ctx/test?mode="+_mode,10,_delay,_length,_send);

View File

@ -170,7 +170,7 @@ public class DataSourceLoginServiceTest
protected void changePassword (String user, String newpwd) throws Exception
{
Loader.loadClass("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
Loader.loadClass("org.apache.derby.jdbc.EmbeddedDriver").getDeclaredConstructor().newInstance();
try (Connection connection = DriverManager.getConnection(DatabaseLoginServiceTestServer.__dbURL, "", "");
Statement stmt = connection.createStatement())
{

View File

@ -92,7 +92,7 @@ public class DatabaseLoginServiceTestServer
//System.err.println("Running script:"+scriptFile.getAbsolutePath());
try (FileInputStream fileStream = new FileInputStream(scriptFile))
{
Loader.loadClass("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
Loader.loadClass("org.apache.derby.jdbc.EmbeddedDriver").getDeclaredConstructor().newInstance();
Connection connection = DriverManager.getConnection(__dbURL, "", "");
ByteArrayOutputStream out = new ByteArrayOutputStream();
return ij.runScript(connection, fileStream, "UTF-8", out, "UTF-8");

View File

@ -295,7 +295,8 @@ public class Dump extends HttpServlet
{
try
{
throw (Throwable) Thread.currentThread().getContextClassLoader().loadClass(info.substring(1)).newInstance();
throw (Throwable) Thread.currentThread().getContextClassLoader()
.loadClass(info.substring(1)).getDeclaredConstructor().newInstance();
}
catch (Throwable th)
{