本文整理汇总了Java中java.lang.reflect.Constructor类的典型用法代码示例。如果您正苦于以下问题:Java Constructor类的具体用法?Java Constructor怎么用?Java Constructor使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Constructor类属于java.lang.reflect包,在下文中一共展示了Constructor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: findConstructor
import java.lang.reflect.Constructor; //导入依赖的package包/类
public static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType)
throws NoSuchMethodException {
Constructor<?> targetConstructor;
try {
targetConstructor = clazz.getConstructor(new Class<?>[] {paramType});
} catch (NoSuchMethodException e) {
targetConstructor = null;
Constructor<?>[] constructors = clazz.getConstructors();
for (Constructor<?> constructor : constructors) {
if (Modifier.isPublic(constructor.getModifiers())
&& constructor.getParameterTypes().length == 1
&& constructor.getParameterTypes()[0].isAssignableFrom(paramType)) {
targetConstructor = constructor;
break;
}
}
if (targetConstructor == null) {
throw e;
}
}
return targetConstructor;
}
示例2: newFactory
import java.lang.reflect.Constructor; //导入依赖的package包/类
/**
* Retrieves a new HsqlSocketFactory whose class
* is determined by the implClass argument. The basic contract here
* is that implementations constructed by this method should return
* true upon calling isSecure() iff they actually create secure sockets.
* There is no way to guarantee this directly here, so it is simply
* trusted that an implementation is secure if it returns true
* for calls to isSecure();
*
* @return a new secure socket factory
* @param implClass the fully qaulified name of the desired
* class to construct
* @throws Exception if a new secure socket factory cannot
* be constructed
*/
private static HsqlSocketFactory newFactory(String implClass)
throws Exception {
Class clazz;
Constructor ctor;
Class[] ctorParm;
Object[] ctorArg;
Object factory;
clazz = Class.forName(implClass);
ctorParm = new Class[0];
// protected constructor
ctor = clazz.getDeclaredConstructor(ctorParm);
ctorArg = new Object[0];
try {
factory = ctor.newInstance(ctorArg);
} catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
throw (t instanceof Exception) ? ((Exception) t)
: new RuntimeException(
t.toString());
}
return (HsqlSocketFactory) factory;
}
示例3: compile
import java.lang.reflect.Constructor; //导入依赖的package包/类
public NMethod compile(int level) {
String directive = "[{ match: \"" + executable.getDeclaringClass().getName().replace('.', '/')
+ "." + (executable instanceof Constructor ? "<init>" : executable.getName())
+ "\", " + "BackgroundCompilation: false }]";
if (WB.addCompilerDirective(directive) != 1) {
throw new Error("Failed to add compiler directive: " + directive);
}
boolean enqueued = WB.enqueueMethodForCompilation(executable,
level, bci);
if (!enqueued) {
throw new Error(String.format(
"%s can't be enqueued for %scompilation on level %d",
executable, bci >= 0 ? "osr-" : "", level));
}
Utils.waitForCondition(() -> WB.isMethodCompiled(executable, isOsr));
return NMethod.get(executable, isOsr);
}
示例4: JSONORM
import java.lang.reflect.Constructor; //导入依赖的package包/类
/**
* Creates a new JSON ORM by using the class.
* @param clazz The class of the container that will be worked with.
* @throws IllegalArgumentException If the provided class has no empty constructor.
* @throws IllegalStateException If the provided class could not be instantiated.
*/
JSONORM(Class<T> clazz)
throws IllegalArgumentException {
Constructor<?> constructor = null;
for(Constructor<?> tConstructor : clazz.getDeclaredConstructors()) {
if(tConstructor.getParameterCount() == 0) {
constructor = tConstructor;
}
}
if(constructor == null) {
throw new IllegalArgumentException("Provided class " + clazz + " has no empty constructor");
}
constructor.setAccessible(true);
try {
//noinspection unchecked
container = (T) constructor.newInstance();
} catch(InvocationTargetException | InstantiationException | IllegalAccessException exception) {
throw new IllegalStateException("An internal error occurred, could not instantiate " + clazz);
}
}
示例5: get
import java.lang.reflect.Constructor; //导入依赖的package包/类
public static ICrypt get(String name, String password) {
String className = crypts.get(name);
if (className == null) {
return null;
}
try {
Class<?> clazz = Class.forName(className);
Constructor<?> constructor = clazz.getConstructor(String.class,
String.class);
return (ICrypt) constructor.newInstance(name, password);
} catch (Exception e) {
logger.error("get crypt error", e);
}
return null;
}
示例6: getClientCnxnSocket
import java.lang.reflect.Constructor; //导入依赖的package包/类
private ClientCnxnSocket getClientCnxnSocket() throws IOException {
String clientCnxnSocketName = getClientConfig().getProperty(
ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET);
if (clientCnxnSocketName == null) {
clientCnxnSocketName = ClientCnxnSocketNIO.class.getName();
}
try {
Constructor<?> clientCxnConstructor = Class.forName(clientCnxnSocketName).getDeclaredConstructor(ZKClientConfig.class);
ClientCnxnSocket clientCxnSocket = (ClientCnxnSocket) clientCxnConstructor.newInstance(getClientConfig());
return clientCxnSocket;
} catch (Exception e) {
IOException ioe = new IOException("Couldn't instantiate "
+ clientCnxnSocketName);
ioe.initCause(e);
throw ioe;
}
}
示例7: sortConstructors
import java.lang.reflect.Constructor; //导入依赖的package包/类
/**
* Sort the given constructors, preferring public constructors and "greedy" ones with
* a maximum number of arguments. The result will contain public constructors first,
* with decreasing number of arguments, then non-public constructors, again with
* decreasing number of arguments.
* @param constructors the constructor array to sort
*/
public static void sortConstructors(Constructor<?>[] constructors) {
Arrays.sort(constructors, new Comparator<Constructor<?>>() {
@Override
public int compare(Constructor<?> c1, Constructor<?> c2) {
boolean p1 = Modifier.isPublic(c1.getModifiers());
boolean p2 = Modifier.isPublic(c2.getModifiers());
if (p1 != p2) {
return (p1 ? -1 : 1);
}
int c1pl = c1.getParameterTypes().length;
int c2pl = c2.getParameterTypes().length;
return (new Integer(c1pl)).compareTo(c2pl) * -1;
}
});
}
示例8: test7
import java.lang.reflect.Constructor; //导入依赖的package包/类
@Test
@Points("100.1")
public void test7() {
Constructor densityKonstruktori = ReflectionUtils.requireConstructor(clazz, double.class);
Object inst = null;
try {
inst = ReflectionUtils.invokeConstructor(densityKonstruktori, 1.0);
} catch (Throwable ex) {
fail("Ensure that class " + tahtitaivasLuokka + " has constructor public " + tahtitaivasLuokka + "(double density).");
}
int tahdet = 0;
Method m = ReflectionUtils.requireMethod(clazz, printLineMetodi);
try {
ReflectionUtils.invokeMethod(void.class, m, inst);
String out = stdio.getSysOut();
if (out == null || out.isEmpty()) {
fail("Ensure that the method " + printLineMetodi + " prints something.");
}
} catch (Throwable t) {
fail("Ensure that class " + tahtitaivasLuokka + " has method public void " + printLineMetodi + "() "
+ "\nCall to the method should print something");
}
}
示例9: getObject
import java.lang.reflect.Constructor; //导入依赖的package包/类
public Object getObject(final String command) throws Exception {
final Object templates = Gadgets.createTemplatesImpl(command);
final ObjectFactory objectFactoryProxy =
Gadgets.createMemoitizedProxy(Gadgets.createMap("getObject", templates), ObjectFactory.class);
final Type typeTemplatesProxy = Gadgets.createProxy((InvocationHandler)
Reflections.getFirstCtor("org.springframework.beans.factory.support.AutowireUtils$ObjectFactoryDelegatingInvocationHandler")
.newInstance(objectFactoryProxy), Type.class, Templates.class);
final Object typeProviderProxy = Gadgets.createMemoitizedProxy(
Gadgets.createMap("getType", typeTemplatesProxy),
forName("org.springframework.core.SerializableTypeWrapper$TypeProvider"));
final Constructor mitpCtor = Reflections.getFirstCtor("org.springframework.core.SerializableTypeWrapper$MethodInvokeTypeProvider");
final Object mitp = mitpCtor.newInstance(typeProviderProxy, Object.class.getMethod("getClass", new Class[] {}), 0);
Reflections.setFieldValue(mitp, "methodName", "newTransformer");
return mitp;
}
示例10: onCreateViewHolder
import java.lang.reflect.Constructor; //导入依赖的package包/类
@Override
public EntryHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(sKnownViewHolderLayouts.get(type), viewGroup, false);
try {
try {
return sKnownViewHolders.get(type).getDeclaredConstructor(View.class).newInstance(view);
} catch (NoSuchMethodException e2) {
for (Constructor constructor : sKnownViewHolders.get(type).getDeclaredConstructors()) {
Class[] p = constructor.getParameterTypes();
if (p.length == 2 && p[0].equals(View.class) && EntryRecyclerViewAdapter.class.isAssignableFrom(p[1]))
return (EntryHolder) constructor.newInstance(view, this);
}
throw new NoSuchMethodException();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
示例11: newInstance
import java.lang.reflect.Constructor; //导入依赖的package包/类
/**
* Create an object for the given class and initialize it from conf.
* @param theClass class of which an object is created
* @param conf Configuration
* @return a new object
*/
@SuppressWarnings("unchecked")
static <T> T newInstance(Class<T> theClass,
URI uri, Configuration conf) {
T result;
try {
Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(theClass);
if (meth == null) {
meth = theClass.getDeclaredConstructor(URI_CONFIG_ARGS);
meth.setAccessible(true);
CONSTRUCTOR_CACHE.put(theClass, meth);
}
result = meth.newInstance(uri, conf);
} catch (Exception e) {
throw new RuntimeException(e);
}
return result;
}
示例12: newInstanceDataBase
import java.lang.reflect.Constructor; //导入依赖的package包/类
/**
* 利用反射构建DataBase对象
* @param connInfo
* @return DataBase
*/
public static <T extends Enum<T> & IDataSource> DataBase newInstanceDataBase(ConnectionInfo connInfo)
{
try
{
Constructor<?> dataBaseConstr = connInfo.getIDataSource().getDataBase().getDeclaredConstructor(ConnectionInfo.class);
DataBase dataBase= (DataBase) dataBaseConstr.newInstance(connInfo);
return dataBase;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
DBCException.logException(DBCException.E_newInstanceDataBase, e);
return null;
}
}
示例13: getAccessibleConstructor
import java.lang.reflect.Constructor; //导入依赖的package包/类
/**
* Returns accessible version of the given constructor.
* @param <T> the type of the constructor
* @param ctor prototype constructor object.
* @return <code>null</code> if accessible constructor can not be found.
* @see java.lang.SecurityManager
*/
public static <T> Constructor<T> getAccessibleConstructor(final Constructor<T> ctor) {
// Make sure we have a method to check
if (ctor == null) {
return (null);
}
// If the requested method is not public we cannot call it
if (!Modifier.isPublic(ctor.getModifiers())) {
return (null);
}
// If the declaring class is public, we are done
final Class<T> clazz = ctor.getDeclaringClass();
if (Modifier.isPublic(clazz.getModifiers())) {
return (ctor);
}
// what else can we do?
return null;
}
示例14: create
import java.lang.reflect.Constructor; //导入依赖的package包/类
/**
* Create a specific instance of AppleImage. This has been coded
* using Reflection to ease native compilation for the most part.
*/
public static AppleImage create(int width, int height) {
String[] classes = {
"ImageIoImage", "SunJpegImage", "SwtImage" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
Class[] constructorArgClasses = new Class[] {
int.class, int.class };
Object[] constructorArgs = new Object[] {
new Integer(width), new Integer(height) };
for (int i=0; i<classes.length; i++) {
try {
Class appleImageClass = Class.forName(
"com.webcodepro.applecommander.storage.filters.imagehandlers." //$NON-NLS-1$
+ classes[i]);
Constructor constructor =
appleImageClass.getConstructor(constructorArgClasses);
AppleImage appleImage = (AppleImage)
constructor.newInstance(constructorArgs);
return appleImage;
} catch (Exception ignored) {
// There are multiple exceptions that can be thrown here.
// For the most part, this is expected and simply means that
// the image handler is not available on the platform.
}
}
return null;
}
示例15: createNewDummy
import java.lang.reflect.Constructor; //导入依赖的package包/类
/**
* Creates a new dummy entity of the required type. Required non null foreign keys will be taken from the {@link #getDummy(AbstractRedG, Class)} method
* and will be created if necessary as well. If the creation fails for some reason, a {@link DummyCreationException} will be thrown.
*
* @param redG The redG instance
* @param dummyClass The class specifying the wanted entity type
* @param <T> The wanted entity type
* @return A new dummy entity of the required type. It has already been added to the redG object and can be used immediately.
* @throws DummyCreationException If no fitting constructor is found or instantiation fails
*/
private <T extends RedGEntity> T createNewDummy(AbstractRedG redG, Class<T> dummyClass) {
Constructor constructor = Arrays.stream(dummyClass.getDeclaredConstructors())
.filter(this::isDummyRedGEntityConstructor)
.findFirst().orElseThrow(() -> new DummyCreationException("Could not find a fitting constructor"));
Object[] parameter = new Object[constructor.getParameterCount()];
parameter[0] = redG;
for (int i = 1; i < constructor.getParameterCount(); i++) {
parameter[i] = getDummy(redG, constructor.getParameterTypes()[i]);
}
try {
constructor.setAccessible(true);
T obj = dummyClass.cast(constructor.newInstance(parameter));
redG.addEntity(obj);
return obj;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new DummyCreationException("Instantiation of the dummy failed", e);
}
}