下面列出了org.springframework.util.ClassUtils#getConstructorIfAvailable ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Attempt to create a copy of the supplied {@code TestContext} using its
* <em>copy constructor</em>.
*/
private static TestContext copyTestContext(TestContext testContext) {
Constructor<? extends TestContext> constructor =
ClassUtils.getConstructorIfAvailable(testContext.getClass(), testContext.getClass());
if (constructor != null) {
try {
ReflectionUtils.makeAccessible(constructor);
return constructor.newInstance(testContext);
}
catch (Exception ex) {
if (logger.isInfoEnabled()) {
logger.info(String.format("Failed to invoke copy constructor for [%s]; " +
"concurrent test execution is therefore likely not supported.",
testContext), ex);
}
}
}
// Fallback to original instance
return testContext;
}
/**
* Attempt to create a copy of the supplied {@code TestContext} using its
* <em>copy constructor</em>.
*/
private static TestContext copyTestContext(TestContext testContext) {
Constructor<? extends TestContext> constructor =
ClassUtils.getConstructorIfAvailable(testContext.getClass(), testContext.getClass());
if (constructor != null) {
try {
ReflectionUtils.makeAccessible(constructor);
return constructor.newInstance(testContext);
}
catch (Exception ex) {
if (logger.isInfoEnabled()) {
logger.info(String.format("Failed to invoke copy constructor for [%s]; " +
"concurrent test execution is therefore likely not supported.",
testContext), ex);
}
}
}
// Fallback to original instance
return testContext;
}
private static SolrClient cloneCloudSolrClient(SolrClient solrClient, String core) {
if (VersionUtil.isSolr3XAvailable() || solrClient == null) {
return null;
}
CloudSolrClient cloudServer = (CloudSolrClient) solrClient;
String zkHost = readField(solrClient, "zkHost");
Constructor<? extends SolrClient> constructor = (Constructor<? extends SolrClient>) ClassUtils
.getConstructorIfAvailable(solrClient.getClass(), String.class, LBHttpSolrClient.class);
CloudSolrClient clone = (CloudSolrClient) BeanUtils.instantiateClass(constructor, zkHost,
cloneLBHttpSolrClient(cloudServer.getLbClient(), core));
if (org.springframework.util.StringUtils.hasText(core)) {
clone.setDefaultCollection(core);
}
return clone;
}
private static HttpClient cloneHttpClient(HttpClient sourceClient)
throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
if (sourceClient == null) {
return null;
}
Class<?> clientType = ClassUtils.getUserClass(sourceClient);
Constructor<?> constructor = ClassUtils.getConstructorIfAvailable(clientType, HttpParams.class);
if (constructor != null) {
HttpClient targetClient = (HttpClient) constructor.newInstance(sourceClient.getParams());
BeanUtils.copyProperties(sourceClient, targetClient);
return targetClient;
} else {
return new DefaultHttpClient(sourceClient.getParams());
}
}
@Override
public Object clone(Object entity) {
Class clazz = entity.getClass();
Constructor copyCtor = ClassUtils.getConstructorIfAvailable(clazz, clazz);
if (copyCtor == null) {
throw new LockingAndVersioningException(format("no copy constructor: %s", clazz.getCanonicalName()));
}
Object newInstance = null;
try {
newInstance = copyCtor.newInstance(entity);
} catch (Exception e) {
throw new LockingAndVersioningException("copy constructor failed", e);
}
return newInstance;
}
@Override
public MimeMessage createMimeMessage() {
// We have to use reflection as SmartMimeMessage is not package-private
if (ClassUtils.isPresent(SMART_MIME_MESSAGE_CLASS_NAME,
ClassUtils.getDefaultClassLoader())) {
Class<?> smartMimeMessage = ClassUtils.resolveClassName(
SMART_MIME_MESSAGE_CLASS_NAME, ClassUtils.getDefaultClassLoader());
Constructor<?> constructor = ClassUtils.getConstructorIfAvailable(
smartMimeMessage, Session.class, String.class, FileTypeMap.class);
if (constructor != null) {
Object mimeMessage = BeanUtils.instantiateClass(constructor, getSession(),
this.defaultEncoding, this.defaultFileTypeMap);
return (MimeMessage) mimeMessage;
}
}
return new MimeMessage(getSession());
}
@Override
@SuppressWarnings("unchecked")
public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, ProjectionFactory factory,
NamedQueries namedQueries) {
QueryMethod queryMethod = new QueryMethod(method, metadata, factory);
Constructor<? extends KeyValuePartTreeQuery> constructor = (Constructor<? extends KeyValuePartTreeQuery>) ClassUtils
.getConstructorIfAvailable(this.repositoryQueryType, QueryMethod.class,
QueryMethodEvaluationContextProvider.class, KeyValueOperations.class, Class.class);
Assert.state(constructor != null,
String.format(
"Constructor %s(QueryMethod, EvaluationContextProvider, KeyValueOperations, Class) not available!",
ClassUtils.getShortName(this.repositoryQueryType)));
return BeanUtils.instantiateClass(constructor, queryMethod, evaluationContextProvider, this.keyValueOperations,
this.queryCreator);
}
/**
* Creates a request control using the constructor parameters given in
* <code>params</code>.
* @param paramTypes Types of the constructor parameters
* @param params Actual constructor parameters
* @return Control to be used by the DirContextProcessor
*/
public Control createRequestControl(Class<?>[] paramTypes, Object[] params) {
Constructor<?> constructor = ClassUtils.getConstructorIfAvailable(requestControlClass, paramTypes);
if (constructor == null) {
throw new IllegalArgumentException("Failed to find an appropriate RequestControl constructor");
}
Control result = null;
try {
result = (Control) constructor.newInstance(params);
}
catch (Exception e) {
ReflectionUtils.handleReflectionException(e);
}
return result;
}
public Control createRequestControl() {
byte[] actualCookie = null;
if (cookie != null) {
actualCookie = cookie.getCookie();
}
Constructor constructor = ClassUtils.getConstructorIfAvailable(requestControlClass, new Class[] { int.class,
byte[].class, boolean.class });
if (constructor == null) {
throw new IllegalArgumentException("Failed to find an appropriate RequestControl constructor");
}
Control result = null;
try {
result = (Control) constructor.newInstance(pageSize, actualCookie,
critical);
}
catch (Exception e) {
ReflectionUtils.handleReflectionException(e);
}
return result;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static SolrClient cloneEmbeddedSolrServer(SolrClient solrClient, String core) {
CoreContainer coreContainer = ((EmbeddedSolrServer) solrClient).getCoreContainer();
try {
Constructor constructor = ClassUtils.getConstructorIfAvailable(solrClient.getClass(), CoreContainer.class,
String.class);
return (SolrClient) BeanUtils.instantiateClass(constructor, coreContainer, core);
} catch (Exception e) {
throw new BeanInstantiationException(solrClient.getClass(),
"Cannot create instace of " + solrClient.getClass() + ".", e);
}
}
private Constructor<?> getCustomCtor(Class<?> type) {
for (Constructor<?> ctor : type.getDeclaredConstructors()) {
if (ctor.isAnnotationPresent(DynamicComponent.class) && !isJsonConstructor(ctor)) {
return ctor;
}
}
return ClassUtils.getConstructorIfAvailable(type);
}
/**
* Create the BeanContainer to use.
* @param beanClass bean type in container
* @param data intial data.
* @return a new BeanContainer
*/
protected Container createBeanContainer(Class<T> beanClass, List<T> data) {
Constructor<?extends Container> ctor =
ClassUtils.getConstructorIfAvailable(this.containerClass, Class.class, Collection.class);
if (ctor != null)
return BeanUtils.instantiateClass(ctor, beanClass, data);
return new BeanItemContainer<T>(beanClass, data);
}
@Nullable
private static Constructor<?> determineFactoryConstructor(Class<?> targetClass, Class<?> sourceClass) {
return ClassUtils.getConstructorIfAvailable(targetClass, sourceClass);
}
@Nullable
private static Constructor<?> determineFactoryConstructor(Class<?> targetClass, Class<?> sourceClass) {
return ClassUtils.getConstructorIfAvailable(targetClass, sourceClass);
}
private static Constructor<?> determineFactoryConstructor(Class<?> targetClass, Class<?> sourceClass) {
return ClassUtils.getConstructorIfAvailable(targetClass, sourceClass);
}
private static Constructor<?> determineFactoryConstructor(Class<?> targetClass, Class<?> sourceClass) {
return ClassUtils.getConstructorIfAvailable(targetClass, sourceClass);
}
public DashboardExtensionsPanel(
final String id, final List<Class<? extends BaseExtWidget>> extWidgetClasses, final PageReference pageRef) {
super(id);
List<BaseExtWidget> instances = new ArrayList<>();
for (final Class<? extends BaseExtWidget> clazz : extWidgetClasses) {
final Constructor<? extends BaseExtWidget> constructor =
ClassUtils.getConstructorIfAvailable(clazz, String.class, PageReference.class);
if (constructor == null) {
LOG.error("Could not find required construtor in {}, ignoring", clazz);
} else {
try {
instances.add(constructor.newInstance("widget", pageRef));
} catch (Exception e) {
LOG.error("While creating instance of {}", clazz, e);
}
}
}
ListView<BaseExtWidget> widgets = new ListView<BaseExtWidget>("widgets", instances) {
private static final long serialVersionUID = 4949588177564901031L;
@Override
protected void populateItem(final ListItem<BaseExtWidget> item) {
WebMarkupContainer widgetContainer = new WebMarkupContainer("widgetContainer");
widgetContainer.setOutputMarkupId(true);
ExtWidget ann = item.getModelObject().getClass().getAnnotation(ExtWidget.class);
if (ann != null) {
widgetContainer.add(new AttributeModifier("class", ann.cssClass()));
}
item.add(widgetContainer);
item.getModelObject().setOutputMarkupId(true);
widgetContainer.add(item.getModelObject());
}
};
add(widgets);
}
ConstructorCachingQueryCreatorFactory(Class<? extends AbstractQueryCreator<?, ?>> type) {
this.type = type;
this.constructor = ClassUtils.getConstructorIfAvailable(type, PartTree.class, ParameterAccessor.class);
}
/**
* Create {@link org.apache.solr.core.CoreContainer} via its constructor
* (Solr 3.6.0 - 4.3.1)
*
* @param solrHomeDirectory
* @param solrXmlFile
* @return
*/
private CoreContainer createCoreContainerViaConstructor(String solrHomeDirectory, File solrXmlFile) {
Constructor<CoreContainer> constructor = ClassUtils.getConstructorIfAvailable(CoreContainer.class, String.class,
File.class);
return BeanUtils.instantiateClass(constructor, solrHomeDirectory, solrXmlFile);
}