Skip to content

Commit

Permalink
Replace newInstance() with getDeclaredConstructor().newInstance() (ap…
Browse files Browse the repository at this point in the history
…ache#12094)

* Replace newInstance() with getDeclaredConstructor().newInstance()

* Format code
  • Loading branch information
yuruguo authored Sep 20, 2021
1 parent 9975fe4 commit 69abf98
Show file tree
Hide file tree
Showing 29 changed files with 55 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ static Pair<NarClassLoader, LedgerOffloaderFactory> getOffloaderFactory(String n
Thread loadingThread = new Thread(() -> {
Thread.currentThread().setContextClassLoader(ncl);
try {
Object offloader = factoryClass.newInstance();
Object offloader = factoryClass.getDeclaredConstructor().newInstance();
if (!(offloader instanceof LedgerOffloaderFactory)) {
throw new IOException("Class " + conf.getOffloaderFactoryClass() + " does not implement interface "
+ LedgerOffloaderFactory.class.getName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ public AuthenticationService(ServiceConfiguration conf) throws PulsarServerExcep
if (className.isEmpty()) {
continue;
}
AuthenticationProvider provider = (AuthenticationProvider) Class.forName(className).newInstance();
AuthenticationProvider provider = (AuthenticationProvider) Class.forName(className)
.getDeclaredConstructor().newInstance();

List<AuthenticationProvider> providerList = providerMap.get(provider.getAuthMethodName());
if (null == providerList) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ public AuthorizationService(ServiceConfiguration conf, PulsarResources pulsarRes
try {
final String providerClassname = conf.getAuthorizationProvider();
if (StringUtils.isNotBlank(providerClassname)) {
provider = (AuthorizationProvider) Class.forName(providerClassname).newInstance();
provider = (AuthorizationProvider) Class.forName(providerClassname)
.getDeclaredConstructor().newInstance();
provider.initialize(conf, pulsarResources);
log.info("{} has been loaded.", providerClassname);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ public AdditionalServletWithClassLoader load(

try {
Class additionalServletClass = ncl.loadClass(def.getAdditionalServletClass());
Object additionalServlet = additionalServletClass.newInstance();
Object additionalServlet = additionalServletClass.getDeclaredConstructor().newInstance();
if (!(additionalServlet instanceof AdditionalServlet)) {
throw new IOException("Class " + def.getAdditionalServletClass()
+ " does not implement additional servlet interface");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Map;
Expand Down Expand Up @@ -94,10 +95,11 @@ public static <T extends PulsarConfiguration> T create(Properties properties,
checkNotNull(properties);
T configuration = null;
try {
configuration = (T) clazz.newInstance();
configuration = (T) clazz.getDeclaredConstructor().newInstance();
configuration.setProperties(properties);
update((Map) properties, configuration);
} catch (InstantiationException | IllegalAccessException e) {
} catch (InstantiationException | IllegalAccessException
| NoSuchMethodException | InvocationTargetException e) {
throw new IllegalArgumentException("Failed to instantiate " + clazz.getName(), e);
}
return configuration;
Expand Down Expand Up @@ -177,7 +179,8 @@ private static boolean isEmpty(Object obj) {
*/
public static ServiceConfiguration convertFrom(PulsarConfiguration conf, boolean ignoreNonExistMember) throws RuntimeException {
try {
final ServiceConfiguration convertedConf = ServiceConfiguration.class.newInstance();
final ServiceConfiguration convertedConf = ServiceConfiguration.class
.getDeclaredConstructor().newInstance();
Field[] confFields = conf.getClass().getDeclaredFields();
Arrays.stream(confFields).forEach(confField -> {
try {
Expand All @@ -196,9 +199,8 @@ public static ServiceConfiguration convertFrom(PulsarConfiguration conf, boolean
}
});
return convertedConf;
} catch (InstantiationException e) {
throw new RuntimeException("Exception caused while converting configuration: " + e.getMessage());
} catch (IllegalAccessException e) {
} catch (InstantiationException | IllegalAccessException
| InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException("Exception caused while converting configuration: " + e.getMessage());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1213,7 +1213,7 @@ public synchronized LedgerOffloader createManagedLedgerOffloader(OffloadPolicies

private SchemaStorage createAndStartSchemaStorage() throws Exception {
final Class<?> storageClass = Class.forName(config.getSchemaRegistryStorageClassName());
Object factoryInstance = storageClass.newInstance();
Object factoryInstance = storageClass.getDeclaredConstructor().newInstance();
Method createMethod = storageClass.getMethod("create", PulsarService.class);
SchemaStorage schemaStorage = (SchemaStorage) createMethod.invoke(factoryInstance, this);
schemaStorage.start();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public static DelayedDeliveryTrackerFactory loadDelayedDeliveryTrackerFactory(Se
Class<?> factoryClass;
try {
factoryClass = Class.forName(conf.getDelayedDeliveryTrackerFactoryClassName());
Object obj = factoryClass.newInstance();
Object obj = factoryClass.getDeclaredConstructor().newInstance();
checkArgument(obj instanceof DelayedDeliveryTrackerFactory,
"The factory has to be an instance of " + DelayedDeliveryTrackerFactory.class.getName());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ BrokerInterceptorWithClassLoader load(BrokerInterceptorMetadata metadata, String

try {
Class interceptorClass = ncl.loadClass(def.getInterceptorClass());
Object interceptor = interceptorClass.newInstance();
Object interceptor = interceptorClass.getDeclaredConstructor().newInstance();
if (!(interceptor instanceof BrokerInterceptor)) {
throw new IOException("Class " + def.getInterceptorClass()
+ " does not implement broker interceptor interface");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ static LoadManager create(final PulsarService pulsar) {
final ServiceConfiguration conf = pulsar.getConfiguration();
final Class<?> loadManagerClass = Class.forName(conf.getLoadManagerClassName());
// Assume there is a constructor with one argument of PulsarService.
final Object loadManagerInstance = loadManagerClass.newInstance();
final Object loadManagerInstance = loadManagerClass.getDeclaredConstructor().newInstance();
if (loadManagerInstance instanceof LoadManager) {
final LoadManager casted = (LoadManager) loadManagerInstance;
casted.initialize(pulsar);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ public void accept(Notification t) {
private LoadSheddingStrategy createLoadSheddingStrategy() {
try {
Class<?> loadSheddingClass = Class.forName(conf.getLoadBalancerLoadSheddingStrategy());
Object loadSheddingInstance = loadSheddingClass.newInstance();
Object loadSheddingInstance = loadSheddingClass.getDeclaredConstructor().newInstance();
if (loadSheddingInstance instanceof LoadSheddingStrategy) {
return (LoadSheddingStrategy) loadSheddingInstance;
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ static ProtocolHandlerWithClassLoader load(ProtocolHandlerMetadata metadata,

try {
Class handlerClass = ncl.loadClass(phDef.getHandlerClass());
Object handler = handlerClass.newInstance();
Object handler = handlerClass.getDeclaredConstructor().newInstance();
if (!(handler instanceof ProtocolHandler)) {
throw new IOException("Class " + phDef.getHandlerClass()
+ " does not implement protocol handler interface");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ static Map<SchemaType, SchemaCompatibilityCheck> getCheckers(Set<String> checker
Map<SchemaType, SchemaCompatibilityCheck> checkers = Maps.newHashMap();
for (String className : checkerClasses) {
final Class<?> checkerClass = Class.forName(className);
SchemaCompatibilityCheck instance = (SchemaCompatibilityCheck) checkerClass.newInstance();
SchemaCompatibilityCheck instance = (SchemaCompatibilityCheck) checkerClass
.getDeclaredConstructor().newInstance();
checkers.put(instance.getSchemaType(), instance);
}
return checkers;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ static ManagedLedgerStorage create(ServiceConfiguration conf,
BookKeeperClientFactory bkProvider,
EventLoopGroup eventLoopGroup) throws Exception {
final Class<?> storageClass = Class.forName(conf.getManagedLedgerStorageClassName());
final ManagedLedgerStorage storage = (ManagedLedgerStorage) storageClass.newInstance();
final ManagedLedgerStorage storage = (ManagedLedgerStorage) storageClass.getDeclaredConstructor().newInstance();
storage.initialize(conf, metadataStore, zkClient, bkProvider, eventLoopGroup);
return storage;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ static TransactionBufferProvider newProvider(String providerClassName) throws IO
Class<?> providerClass;
try {
providerClass = Class.forName(providerClassName);
Object obj = providerClass.newInstance();
Object obj = providerClass.getDeclaredConstructor().newInstance();
checkArgument(obj instanceof TransactionBufferProvider,
"The factory has to be an instance of "
+ TransactionBufferProvider.class.getName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ static TransactionPendingAckStoreProvider newProvider(String providerClassName)
Class<?> providerClass;
try {
providerClass = Class.forName(providerClassName);
Object obj = providerClass.newInstance();
Object obj = providerClass.getDeclaredConstructor().newInstance();
checkArgument(obj instanceof TransactionPendingAckStoreProvider,
"The factory has to be an instance of "
+ TransactionPendingAckStoreProvider.class.getName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -630,7 +630,7 @@ private void testAvroFunctionLocalRun(String jarFilePathUrl) throws Exception {
int totalMsgs = 5;
Method setBaseValueMethod = avroTestObjectClass.getMethod("setBaseValue", new Class[]{int.class});
for (int i = 0; i < totalMsgs; i++) {
Object avroTestObject = avroTestObjectClass.newInstance();
Object avroTestObject = avroTestObjectClass.getDeclaredConstructor().newInstance();
setBaseValueMethod.invoke(avroTestObject, i);
producer.newMessage().property(propertyKey, propertyValue)
.value(avroTestObject).send();
Expand Down Expand Up @@ -672,7 +672,8 @@ private void testAvroFunctionLocalRun(String jarFilePathUrl) throws Exception {
.brokerServiceUrl(pulsar.getBrokerServiceUrlTls()).build();
localRunner.start(false);

producer.newMessage().property(propertyKey, propertyValue).value(avroTestObjectClass.newInstance()).send();
producer.newMessage().property(propertyKey, propertyValue).value(avroTestObjectClass
.getDeclaredConstructor().newInstance()).send();
Message<GenericRecord> msg = consumer.receive(2, TimeUnit.SECONDS);
Assert.assertNull(msg);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public class DefaultImplementation {
LongRunningProcessStatus.Status.class, String.class, MessageId.class);

public static PulsarAdminBuilder newAdminClientBuilder() {
return ReflectionUtils.catchExceptions(() -> ADMIN_CLIENT_BUILDER_IMPL.newInstance());
return ReflectionUtils.catchExceptions(() -> ADMIN_CLIENT_BUILDER_IMPL.getDeclaredConstructor().newInstance());
}

public static OffloadProcessStatus newOffloadProcessStatus(LongRunningProcessStatus.Status status, String lastError
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public static final Authentication create(String authPluginClassName, String aut
try {
if (isNotBlank(authPluginClassName)) {
Class<?> authClass = Class.forName(authPluginClassName);
Authentication auth = (Authentication) authClass.newInstance();
Authentication auth = (Authentication) authClass.getDeclaredConstructor().newInstance();
if (auth instanceof EncodedAuthenticationParameterSupport) {
// Parse parameters on plugin side.
((EncodedAuthenticationParameterSupport) auth).configure(authParamsString);
Expand Down Expand Up @@ -104,7 +104,7 @@ public static final Authentication create(String authPluginClassName, Map<String
try {
if (isNotBlank(authPluginClassName)) {
Class<?> authClass = Class.forName(authPluginClassName);
Authentication auth = (Authentication) authClass.newInstance();
Authentication auth = (Authentication) authClass.getDeclaredConstructor().newInstance();
auth.configure(authParams);
return auth;
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/
package org.apache.pulsar.client.api.url;

import java.lang.reflect.InvocationTargetException;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.util.HashMap;
Expand All @@ -40,13 +41,12 @@ public URLStreamHandler createURLStreamHandler(String protocol) {
try {
Class<? extends URLStreamHandler> handler = handlers.get(protocol);
if (handler != null) {
urlStreamHandler = handler.newInstance();
urlStreamHandler = handler.getDeclaredConstructor().newInstance();
} else {
urlStreamHandler = null;
}
} catch (InstantiationException e) {
urlStreamHandler = null;
} catch (IllegalAccessException e) {
} catch (InstantiationException | IllegalAccessException
| InvocationTargetException | NoSuchMethodException e) {
urlStreamHandler = null;
}
return urlStreamHandler;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/
package org.apache.pulsar.common.intercept;

import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import java.util.Set;
import org.apache.pulsar.common.util.ClassLoaderUtils;
Expand All @@ -41,8 +42,9 @@ public static Set<BrokerEntryMetadataInterceptor> loadBrokerEntryMetadataInterce
Class<BrokerEntryMetadataInterceptor> clz = (Class<BrokerEntryMetadataInterceptor>) ClassLoaderUtils
.loadClass(interceptorName, classLoader);
try {
interceptors.add(clz.newInstance());
} catch (InstantiationException | IllegalAccessException e) {
interceptors.add(clz.getDeclaredConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException
| InvocationTargetException | NoSuchMethodException e) {
log.error("Create new BrokerEntryMetadataInterceptor instance for {} failed.",
interceptorName, e);
throw new RuntimeException(e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ public static JvmMetrics create(ScheduledExecutorService executor, String compon
JvmGCMetricsLogger gcLoggerImpl = null;
if (StringUtils.isNotBlank(gcLoggerImplClassName)) {
try {
gcLoggerImpl = (JvmGCMetricsLogger) Class.forName(gcLoggerImplClassName).newInstance();
gcLoggerImpl = (JvmGCMetricsLogger) Class.forName(gcLoggerImplClassName)
.getDeclaredConstructor().newInstance();
} catch (Exception e) {
log.error("Failed to initialize jvmGCMetricsLogger {} due to {}", jvmGCMetricsLoggerClassName,
e.getMessage(), e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ public static Provider getProvider() {
private static Provider loadConscryptProvider() {
Provider provider;
try {
provider = (Provider) Class.forName(CONSCRYPT_PROVIDER_CLASS).newInstance();
provider = (Provider) Class.forName(CONSCRYPT_PROVIDER_CLASS).getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
log.warn("Unable to get security provider for class {}", CONSCRYPT_PROVIDER_CLASS, e);
return null;
Expand Down Expand Up @@ -179,7 +179,7 @@ public static Provider getBCProviderFromClassPath() throws Exception {
clazz = Class.forName(BC_FIPS_PROVIDER_CLASS);
}

Provider provider = (Provider) clazz.newInstance();
Provider provider = (Provider) clazz.getDeclaredConstructor().newInstance();
Security.addProvider(provider);
if (log.isDebugEnabled()) {
log.debug("Found and Instantiated Bouncy Castle provider in classpath {}", provider.getName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ private static void processAnnotations(Annotation[] annotations, String fieldNam
if (hasConstructor(clazz, Map.class)) {
o = clazz.getConstructor(Map.class).newInstance(params);
} else { //If not call default constructor
o = clazz.newInstance();
o = clazz.getDeclaredConstructor().newInstance();
}
o.validateField(fieldName, value);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ static WorkerServiceWithClassLoader load(WorkerServiceMetadata metadata,

try {
Class handlerClass = ncl.loadClass(phDef.getHandlerClass());
Object handler = handlerClass.newInstance();
Object handler = handlerClass.getDeclaredConstructor().newInstance();
if (!(handler instanceof WorkerService)) {
throw new IOException("Class " + phDef.getHandlerClass()
+ " does not implement worker service interface");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ private void loadMonitoring() {
//Not a known type, use FQCN
klass = (Class<? extends MonitorService>) Class.forName(monitorType);
}
this.monitorServer = klass.newInstance();
this.monitorServer = klass.getDeclaredConstructor().newInstance();
Context context = new Context();
for (String key : keys) {
if (key.startsWith(CONF_MONITOR_PREFIX)) {
Expand Down
Loading

0 comments on commit 69abf98

Please sign in to comment.