本文整理汇总了Java中java.lang.reflect.Constructor.newInstance方法的典型用法代码示例。如果您正苦于以下问题:Java Constructor.newInstance方法的具体用法?Java Constructor.newInstance怎么用?Java Constructor.newInstance使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.lang.reflect.Constructor
的用法示例。
在下文中一共展示了Constructor.newInstance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getPlacesBar
import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/** Returns instance of WindowsPlacesBar class or null in case of failure
*/
private JComponent getPlacesBar () {
if (placesBarFailed) {
return null;
}
try {
Class<?> clazz = Class.forName("sun.swing.WindowsPlacesBar");
Class[] params = new Class[] { JFileChooser.class, Boolean.TYPE };
Constructor<?> constr = clazz.getConstructor(params);
return (JComponent)constr.newInstance(fileChooser, isXPStyle().booleanValue());
} catch (Exception exc) {
// reflection not succesfull, just log the exception and return null
Logger.getLogger(DirectoryChooserUI.class.getName()).log(
Level.FINE, "WindowsPlacesBar class can't be instantiated.", exc);
placesBarFailed = true;
return null;
}
}
示例2: testVOGetter
import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
* Each VO member must have a getter, collections must not be initialized
* with null.
*/
@Test
public void testVOGetter() throws Exception {
StringBuffer errors = new StringBuffer();
List<Class<?>> classes = PackageClassReader.getClasses(BaseVO.class,
null, ClassFilter.CLASSES_ONLY);
for (Class<?> clazz : classes) {
Constructor<?> constructor = clazz.getConstructor();
Object voInstance = constructor.newInstance();
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
if (!Modifier.isStatic(field.getModifiers())) {
Object value = getValue(field, voInstance, errors);
if (isCollection(field) && value == null) {
errors.append("Field '").append(field.getName())
.append("' of type '").append(clazz.getName())
.append("' is initialized with null\n");
}
}
}
}
if (errors.length() > 0) {
Assert.fail("\n" + errors.toString());
}
}
示例3: buildWithConstructor
import java.lang.reflect.Constructor; //导入方法依赖的package包/类
@SuppressWarnings({"unchecked"})
public static <T> T buildWithConstructor(Class<T> toBuild, Object... args) {
for (Constructor<?> constructor : toBuild.getDeclaredConstructors()) {
if (constructor.getParameterCount() == args.length) {
try {
return (T) constructor.newInstance(args);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalArgumentException("Couldn't construct a new object of type: " + toBuild + " using it's 0 args constructor!", e);
}
}
}
throw new IllegalArgumentException("No " + args.length + " args constructor found in class: " + toBuild);
}
示例4: createDefaultErrorListener
import java.lang.reflect.Constructor; //导入方法依赖的package包/类
static ErrorListener createDefaultErrorListener() {
try {
Class<?> errorHandler =
Class.forName("com.sun.org.apache.xml.internal.utils.DefaultErrorHandler");
Constructor<?> ctor = errorHandler.getConstructor();
return (ErrorListener) ctor.newInstance();
} catch (Throwable r) {
return new DummyErrorListenerHandler();
}
}
示例5: getInstance
import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
* Méthode getInstance.
* @param clazz
* @return
* @throws SaladiumException
*/
private IWorker getInstance(Class<?> clazz) throws SaladiumException {
IWorker worker;
try {
Constructor<?> cons = getConstructeur(clazz);
cons.setAccessible(true);
worker = (IWorker) cons.newInstance();
Method instance = clazz.getDeclaredMethod("getInstance", (Class<?>[]) null);
worker = (IWorker) instance.invoke(worker, new Object[] {});
} catch (Exception e) {
throw new SaladiumException("Impossible d'instancier le worker", e);
}
return worker;
}
示例6: clone
import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
* Makes unique copies of the vertices and edges into the cloned graph
* @param copy_source
* @throws CloneNotSupportedException
*/
@SuppressWarnings("unchecked")
public void clone(IGraph<V, E> copy_source) throws CloneNotSupportedException {
//
// Copy Vertices
//
for (V v : copy_source.getVertices()) {
this.addVertex(v);
} // FOR
//
// Copy Edges
//
Constructor<E> constructor = null;
try {
for (E edge : copy_source.getEdges()) {
if (constructor == null) {
Class<?> params[] = new Class<?>[] { IGraph.class, AbstractEdge.class };
constructor = (Constructor<E>)ClassUtil.getConstructor(edge.getClass(), params);
}
Pair<V> endpoints = copy_source.getEndpoints(edge);
E new_edge = constructor.newInstance(new Object[]{ this, edge });
this.addEdge(new_edge, endpoints, copy_source.getEdgeType(edge));
} // FOR
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
return;
}
示例7: createPhase
import java.lang.reflect.Constructor; //导入方法依赖的package包/类
public IPhase createPhase(EntityDragon dragon)
{
try
{
Constructor <? extends IPhase > constructor = this.getConstructor();
return (IPhase)constructor.newInstance(new Object[] {dragon});
}
catch (Exception exception)
{
throw new Error(exception);
}
}
示例8: runWithResult
import java.lang.reflect.Constructor; //导入方法依赖的package包/类
public static void runWithResult(Class testCaseClass, String testName) {
try {
Constructor ctor = testCaseClass.getConstructor(new Class[]{
String.class });
TestBase theTest = (TestBase) ctor.newInstance(new Object[]{
testName });
theTest.runWithResult();
} catch (Exception ex) {
System.err.println("couldn't execute test:");
ex.printStackTrace(System.err);
}
}
示例9: allocateDirectBuffer
import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
* Uses internal JDK APIs to allocate a DirectByteBuffer while ignoring the JVM's
* MaxDirectMemorySize limit (the default limit is too low and we do not want to require users
* to increase it).
*/
@SuppressWarnings("unchecked")
public static ByteBuffer allocateDirectBuffer(int size) {
try {
Class cls = Class.forName("java.nio.DirectByteBuffer");
Constructor constructor = cls.getDeclaredConstructor(Long.TYPE, Integer.TYPE);
constructor.setAccessible(true);
Field cleanerField = cls.getDeclaredField("cleaner");
cleanerField.setAccessible(true);
final long memory = allocateMemory(size);
ByteBuffer buffer = (ByteBuffer) constructor.newInstance(memory, size);
Cleaner cleaner = Cleaner.create(buffer, new Runnable() {
@Override
public void run() {
freeMemory(memory);
}
});
cleanerField.set(buffer, cleaner);
return buffer;
} catch (Exception e) {
throwException(e);
}
throw new IllegalStateException("unreachable");
}
示例10: init
import java.lang.reflect.Constructor; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
@Override
public void init(Properties config) {
this.config = config;
log.info("Init with config {}", config);
// initializing sensors and actuators
Properties configDht22 = new Properties();
configDht22.setProperty("min", this.config.getProperty(DeviceConfig.DHT22_TEMPERATURE_MIN));
configDht22.setProperty("max", this.config.getProperty(DeviceConfig.DHT22_TEMPERATURE_MAX));
this.dht22.init(configDht22);
this.valve.init(null);
// getting hostname and port for client connection
String hostname = this.config.getProperty(DeviceConfig.HOSTNAME);
int port = Integer.valueOf(this.config.getProperty(DeviceConfig.PORT));
String serverCert = this.config.getProperty(DeviceConfig.TRANSPORT_SSL_SERVER_CERT);
try {
// getting and creating the transport class to use
Class transportClass = Class.forName(this.config.getProperty(DeviceConfig.TRANSPORT_CLASS));
Constructor constructor = transportClass.getConstructor(String.class, int.class, String.class, Vertx.class);
this.client = (Client) constructor.newInstance(hostname, port, serverCert, this.vertx);
log.info("Using {} as transport", transportClass);
} catch (Exception e) {
log.error("Transport class instantiation error ...", e);
this.client = new AmqpClient(hostname, port, serverCert, this.vertx);
log.info("Using default {} as transport", AmqpClient.class);
}
}
示例11: FunctionImplementationRegistry
import java.lang.reflect.Constructor; //导入方法依赖的package包/类
public FunctionImplementationRegistry(SabotConfig config, ScanResult classpathScan){
Stopwatch w = Stopwatch.createStarted();
logger.debug("Generating function registry.");
functionRegistry = new FunctionRegistry(classpathScan);
Set<Class<? extends PluggableFunctionRegistry>> registryClasses =
classpathScan.getImplementations(PluggableFunctionRegistry.class);
for (Class<? extends PluggableFunctionRegistry> clazz : registryClasses) {
for (Constructor<?> c : clazz.getConstructors()) {
Class<?>[] params = c.getParameterTypes();
if (params.length != 1 || params[0] != SabotConfig.class) {
logger.warn("Skipping PluggableFunctionRegistry constructor {} for class {} since it doesn't implement a " +
"[constructor(SabotConfig)]", c, clazz);
continue;
}
try {
PluggableFunctionRegistry registry = (PluggableFunctionRegistry)c.newInstance(config);
pluggableFuncRegistries.add(registry);
} catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
logger.warn("Unable to instantiate PluggableFunctionRegistry class '{}'. Skipping it.", clazz, e);
}
break;
}
}
logger.info("Function registry loaded. {} functions loaded in {} ms.", functionRegistry.size(), w.elapsed(TimeUnit.MILLISECONDS));
}
示例12: getThrowableException
import java.lang.reflect.Constructor; //导入方法依赖的package包/类
/**
* Returns a rethrowable exception for this task, if available.
* To provide accurate stack traces, if the exception was not
* thrown by the current thread, we try to create a new exception
* of the same type as the one thrown, but with the recorded
* exception as its cause. If there is no such constructor, we
* instead try to use a no-arg constructor, followed by initCause,
* to the same effect. If none of these apply, or any fail due to
* other exceptions, we return the recorded exception, which is
* still correct, although it may contain a misleading stack
* trace.
*
* @return the exception, or null if none
*/
private Throwable getThrowableException() {
int h = System.identityHashCode(this);
ExceptionNode e;
final ReentrantLock lock = exceptionTableLock;
lock.lock();
try {
expungeStaleExceptions();
ExceptionNode[] t = exceptionTable;
e = t[h & (t.length - 1)];
while (e != null && e.get() != this)
e = e.next;
} finally {
lock.unlock();
}
Throwable ex;
if (e == null || (ex = e.ex) == null)
return null;
if (e.thrower != Thread.currentThread().getId()) {
try {
Constructor<?> noArgCtor = null;
// public ctors only
for (Constructor<?> c : ex.getClass().getConstructors()) {
Class<?>[] ps = c.getParameterTypes();
if (ps.length == 0)
noArgCtor = c;
else if (ps.length == 1 && ps[0] == Throwable.class)
return (Throwable)c.newInstance(ex);
}
if (noArgCtor != null) {
Throwable wx = (Throwable)noArgCtor.newInstance();
wx.initCause(ex);
return wx;
}
} catch (Exception ignore) {
}
}
return ex;
}
示例13: onCreateViewHolder
import java.lang.reflect.Constructor; //导入方法依赖的package包/类
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
try {
View view = layoutInflater.inflate(viewType, parent, false);
// El constructor tiene un DrawerAdapter implícito por ser inner class.
Constructor<? extends ViewHolder> constructor = viewHolderTypes.get(viewType).getConstructor(DrawerAdapter.class, View.class);
return constructor.newInstance(this, view);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
示例14: private_constructor
import java.lang.reflect.Constructor; //导入方法依赖的package包/类
@Test
public void private_constructor() throws Exception {
Constructor<CFGPrinter> constructor = CFGPrinter.class.getDeclaredConstructor();
assertThat(constructor.isAccessible()).isFalse();
constructor.setAccessible(true);
constructor.newInstance();
}
示例15: createEngine
import java.lang.reflect.Constructor; //导入方法依赖的package包/类
public static CordovaWebViewEngine createEngine(Context context, CordovaPreferences preferences) {
String className = preferences.getString("webview", SystemWebViewEngine.class.getCanonicalName());
try {
Class<?> webViewClass = Class.forName(className);
Constructor<?> constructor = webViewClass.getConstructor(Context.class, CordovaPreferences.class);
return (CordovaWebViewEngine) constructor.newInstance(context, preferences);
} catch (Exception e) {
throw new RuntimeException("Failed to create webview. ", e);
}
}