Java Code Examples for java.lang.reflect.Constructor.getParameterCount()

The following are Jave code examples for showing how to use getParameterCount() of the java.lang.reflect.Constructor class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: openjdk-jdk10   File: PublicSub.java   View Source Code Vote up 6 votes
public static void checkAccess(AccessibleObject accessibleObject, Object obj)
    throws IllegalAccessException,
           InvocationTargetException,
           InstantiationException
{
    if (accessibleObject instanceof Field) {
        Field field = (Field) accessibleObject;
        field.set(obj, 42);
        field.get(obj);
    } else if (accessibleObject instanceof Method) {
        Method method = (Method) accessibleObject;
        method.invoke(obj);
    } else if (accessibleObject instanceof Constructor) {
        Constructor<?> constructor = (Constructor<?>) accessibleObject;
        Object[] params = new Object[constructor.getParameterCount()];
        constructor.newInstance(params);
    }
}
 
Example 2
Project: jspider   File: DefineLoader.java   View Source Code Vote up 6 votes
private static FieldProcessor getFieldProcessor(Element element) {
    Object[] arguments = getFieldProcessorArguments(element);
    String clazz = getAttribute(element, "class");

    try {
        if (arguments == null || arguments.length == 0) {
            return (FieldProcessor) Class.forName(clazz).newInstance();
        }

        Constructor<?>[] constructors = Class.forName(clazz).getConstructors();
        for (Constructor<?> constructor : constructors) {
            if (arguments.length == constructor.getParameterCount()) {
                return (FieldProcessor) constructor.newInstance(arguments);
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return null;
}
 
Example 3
Project: jspider   File: FieldDefineBeanDefinitionParser.java   View Source Code Vote up 6 votes
private FieldProcessor getFieldProcessor(Element element) {
    Object[] arguments = getFieldProcessorArguments(element);
    String clazz = element.getAttribute("class");

    try {
        if (arguments == null || arguments.length == 0) {
            return (FieldProcessor) Class.forName(clazz).newInstance();
        }

        Constructor<?>[] constructors = Class.forName(clazz).getConstructors();
        for (Constructor<?> constructor : constructors) {
            if (arguments.length == constructor.getParameterCount()) {
                return (FieldProcessor) constructor.newInstance(arguments);
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return null;
}
 
Example 4
Project: openjdk-jdk10   File: PublicSuper.java   View Source Code Vote up 6 votes
public static void checkAccess(AccessibleObject accessibleObject, Object obj)
    throws IllegalAccessException,
           InvocationTargetException,
           InstantiationException
{
    if (accessibleObject instanceof Field) {
        Field field = (Field) accessibleObject;
        field.set(obj, 42);
        field.get(obj);
    } else if (accessibleObject instanceof Method) {
        Method method = (Method) accessibleObject;
        method.invoke(obj);
    } else if (accessibleObject instanceof Constructor) {
        Constructor<?> constructor = (Constructor<?>) accessibleObject;
        Object[] params = new Object[constructor.getParameterCount()];
        constructor.newInstance(params);
    }
}
 
Example 5
Project: openjdk-jdk10   File: Package.java   View Source Code Vote up 6 votes
public static void checkAccess(AccessibleObject accessibleObject, Object obj)
    throws IllegalAccessException,
           InvocationTargetException,
           InstantiationException
{
    if (accessibleObject instanceof Field) {
        Field field = (Field) accessibleObject;
        field.set(obj, 42);
        field.get(obj);
    } else if (accessibleObject instanceof Method) {
        Method method = (Method) accessibleObject;
        method.invoke(obj);
    } else if (accessibleObject instanceof Constructor) {
        Constructor<?> constructor = (Constructor<?>) accessibleObject;
        Object[] params = new Object[constructor.getParameterCount()];
        constructor.newInstance(params);
    }
}
 
Example 6
Project: booter-injector   File: SupplierFactory.java   View Source Code Vote up 6 votes
private static <T> ThrowingSupplier<T> mapConstructorParameters(Constructor<T> constructor, Supplier<?>[] suppliers) {
    switch (constructor.getParameterCount()) {
        case  0: return constructor::newInstance;
        case  1: return () -> constructor.newInstance(suppliers[0].get());
        case  2: return () -> constructor.newInstance(suppliers[0].get(), suppliers[1].get());
        case  3: return () -> constructor.newInstance(suppliers[0].get(), suppliers[1].get(), suppliers[2].get());
        case  4: return () -> constructor.newInstance(suppliers[0].get(), suppliers[1].get(), suppliers[2].get(), suppliers[3].get());
        case  5: return () -> constructor.newInstance(suppliers[0].get(), suppliers[1].get(), suppliers[2].get(), suppliers[3].get(), suppliers[4].get());
        case  6: return () -> constructor.newInstance(suppliers[0].get(), suppliers[1].get(), suppliers[2].get(), suppliers[3].get(), suppliers[4].get(), suppliers[5].get());
        case  7: return () -> constructor.newInstance(suppliers[0].get(), suppliers[1].get(), suppliers[2].get(), suppliers[3].get(), suppliers[4].get(), suppliers[5].get(), suppliers[6].get());
        case  8: return () -> constructor.newInstance(suppliers[0].get(), suppliers[1].get(), suppliers[2].get(), suppliers[3].get(), suppliers[4].get(), suppliers[5].get(), suppliers[6].get(), suppliers[7].get());
        case  9: return () -> constructor.newInstance(suppliers[0].get(), suppliers[1].get(), suppliers[2].get(), suppliers[3].get(), suppliers[4].get(), suppliers[5].get(), suppliers[6].get(), suppliers[7].get(), suppliers[8].get());
        case 10: return () -> constructor.newInstance(suppliers[0].get(), suppliers[1].get(), suppliers[2].get(), suppliers[3].get(), suppliers[4].get(), suppliers[5].get(), suppliers[6].get(), suppliers[7].get(), suppliers[8].get(), suppliers[9].get());
        default:
            //Should not happen, limits are already checked
            return null;
    }
}
 
Example 7
Project: redg   File: DefaultDummyFactory.java   View Source Code Vote up 6 votes
/**
 * 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);
    }
}
 
Example 8
Project: openjdk-jdk10   File: Package.java   View Source Code Vote up 6 votes
public static void checkAccess(AccessibleObject accessibleObject, Object obj)
    throws IllegalAccessException,
           InvocationTargetException,
           InstantiationException
{
    if (accessibleObject instanceof Field) {
        Field field = (Field) accessibleObject;
        field.set(obj, 42);
        field.get(obj);
    } else if (accessibleObject instanceof Method) {
        Method method = (Method) accessibleObject;
        method.invoke(obj);
    } else if (accessibleObject instanceof Constructor) {
        Constructor<?> constructor = (Constructor<?>) accessibleObject;
        Object[] params = new Object[constructor.getParameterCount()];
        constructor.newInstance(params);
    }
}
 
Example 9
Project: gamecraft   File: Reflection.java   View Source Code Vote up 5 votes
@SuppressWarnings({"unchecked"})
public static <T> Constructor<T> getConstructor(Class<T> clazz, Class<?>... params) {
    for (Constructor<?> constructors : clazz.getDeclaredConstructors()) {
        if (constructors.getParameterCount() != params.length) {
            continue;
        }

        if (Reflection.matchParams(constructors.getParameterTypes(), params)) {
            return (Constructor<T>) constructors;
        }
    }

    return clazz.getSuperclass() == null ? null : getConstructor((Class<T>) clazz.getSuperclass(), params);
}
 
Example 10
Project: monarch   File: StoreUtils.java   View Source Code Vote up 5 votes
public static Constructor<?> getTierStoreConstructor(Class<?> clazz)
    throws DefaultConstructorMissingException {
  for (Constructor<?> c : clazz.getConstructors()) {
    if (c.getParameterCount() == 1 && c.getParameterTypes()[0] == String.class) {
      return c;
    }
  }
  throw new DefaultConstructorMissingException("TierStore default Constructor missing.");
}
 
Example 11
Project: VISNode   File: ProcessNode.java   View Source Code Vote up 5 votes
/**
 * Builds a new process
 *
 * @return ImageProcess
 */
private Process buildProcess() {
    try {
        Constructor constructor = processType.getConstructors()[0];
        TypeConverter converter = new TypeConverter();
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < constructor.getParameterCount(); i++) {
            Object input = getInput(processInput.get(i).getName());
            list.add(converter.convert(input, constructor.getParameterTypes()[i]));
        }
        return (Process) constructor.newInstance(list.toArray());
    } catch (IllegalArgumentException | ReflectiveOperationException ex) {
        throw new RuntimeException("Process build fail", ex);
    }
}
 
Example 12
Project: qpp-conversion-tool   File: Registry.java   View Source Code Vote up 5 votes
private Constructor<?> getNoArgsConstructor(Constructor<?>[] constructors) {
	for (Constructor<?> constructor : constructors) {
		if (constructor.getParameterCount() == 0) {
			return constructor;
		}
	}

	return null;
}
 
Example 13
Project: SDgen   File: ReflectionUtils.java   View Source Code Vote up 5 votes
@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);
}
 
Example 14
Project: skylla   File: ClassUtils.java   View Source Code Vote up 5 votes
public static boolean hasNoArgsConstructor(Class clazz) {
    boolean noArgsConstructor = false;
    for (Constructor<?> constructor : clazz.getConstructors()) {
        if (constructor.getParameterCount() == 0) {
            noArgsConstructor = true;
        }
    }

    return noArgsConstructor;
}
 
Example 15
Project: redg   File: DefaultDummyFactory.java   View Source Code Vote up 5 votes
/**
 * Checks whether the constructor matches the standard redG constructor (AbstractRedG as first param  and zero or more classes extending RedGEntity).
 *
 * @param constructor The constructor to check
 * @return {@code true} if the constructor matches the standard redG constructor, {@code false} otherwise
 */
private boolean isDummyRedGEntityConstructor(Constructor constructor) {
    if (constructor.getParameterCount() < 1) {
        return false;
    }
    if (!AbstractRedG.class.isAssignableFrom(constructor.getParameterTypes()[0])) {
        return false;
    }
    for (int i = 1; i < constructor.getParameterCount(); i++) {
        if (!RedGEntity.class.isAssignableFrom(constructor.getParameterTypes()[i])) {
            return false;
        }
    }
    return true;
}
 
Example 16
Project: monarch   File: StoreUtils.java   View Source Code Vote up 5 votes
public static Constructor<?> hasParameterlessPublicConstructor(Class<?> clazz)
    throws DefaultConstructorMissingException {
  for (Constructor<?> constructor : clazz.getConstructors()) {
    if (constructor.getParameterCount() == 0) {
      return constructor;
    }
  }
  throw new DefaultConstructorMissingException("Default constructor missing");
}
 
Example 17
Project: Jenisys3   File: Entity.java   View Source Code Vote up 5 votes
public static Entity createEntity(String name, FullChunk chunk, CompoundTag nbt, Object... args) {
    Entity entity = null;

    if (knownEntities.containsKey(name)) {
        Class<? extends Entity> clazz = knownEntities.get(name);

        if (clazz == null) {
            return null;
        }

        for (Constructor constructor : clazz.getConstructors()) {
            if (entity != null) {
                break;
            }

            if (constructor.getParameterCount() != (args == null ? 2 : args.length + 2)) {
                continue;
            }

            try {
                if (args == null || args.length == 0) {
                    entity = (Entity) constructor.newInstance(chunk, nbt);
                } else {
                    Object[] objects = new Object[args.length + 2];

                    objects[0] = chunk;
                    objects[1] = nbt;
                    System.arraycopy(args, 0, objects, 2, args.length);
                    entity = (Entity) constructor.newInstance(objects);

                }
            } catch (Exception e) {
                MainLogger.getLogger().logException(e);
            }

        }
    }

    return entity;
}
 
Example 18
Project: Nukkit-Java9   File: BlockEntity.java   View Source Code Vote up 4 votes
public static BlockEntity createBlockEntity(String type, FullChunk chunk, CompoundTag nbt, Object... args) {
    type = type.replaceFirst("BlockEntity", ""); //TODO: Remove this after the first release
    BlockEntity blockEntity = null;

    if (knownBlockEntities.containsKey(type)) {
        Class<? extends BlockEntity> clazz = knownBlockEntities.get(type);

        if (clazz == null) {
            return null;
        }

        for (Constructor constructor : clazz.getConstructors()) {
            if (blockEntity != null) {
                break;
            }

            if (constructor.getParameterCount() != (args == null ? 2 : args.length + 2)) {
                continue;
            }

            try {
                if (args == null || args.length == 0) {
                    blockEntity = (BlockEntity) constructor.newInstance(chunk, nbt);
                } else {
                    Object[] objects = new Object[args.length + 2];

                    objects[0] = chunk;
                    objects[1] = nbt;
                    System.arraycopy(args, 0, objects, 2, args.length);
                    blockEntity = (BlockEntity) constructor.newInstance(objects);

                }
            } catch (Exception e) {
                //ignore
            }

        }
    }

    return blockEntity;
}
 
Example 19
Project: incubator-netbeans   File: JackpotTrees.java   View Source Code Vote up 4 votes
public static <T> T createInstance(Context ctx, Class<T> clazz, Name ident, JCIdent jcIdent, Class<?>[] requiredConstructor, Object[] params) {
    try {
        Class<?> fake = baseClass2Impl.get(clazz);

        if (fake == null) {
            Method visitIdent = Visitor.class.getDeclaredMethod("visitIdent", JCIdent.class);
            Method visitIdentifier = TreeVisitor.class.getDeclaredMethod("visitIdentifier", IdentifierTree.class, Object.class);
            Method toString = Object.class.getDeclaredMethod("toString");
            fake = new ByteBuddy()
                    .subclass(clazz)
                    .implement(IdentifierTree.class)
                    .defineField("ident", Name.class, Visibility.PUBLIC)
                    .defineField("jcIdent", JCIdent.class, Visibility.PUBLIC)
                    .method(ElementMatchers.named("getName")).intercept(FieldAccessor.ofField("ident"))
                    .method(ElementMatchers.named("getKind")).intercept(FixedValue.value(Kind.IDENTIFIER))
                    .method(ElementMatchers.named("accept").and(ElementMatchers.takesArguments(Visitor.class))).intercept(MethodCall.invoke(visitIdent).onArgument(0).withField("jcIdent"))
                    .method(ElementMatchers.named("accept").and(ElementMatchers.takesArgument(0, TreeVisitor.class))).intercept(MethodCall.invoke(visitIdentifier).onArgument(0).withThis().withArgument(1))
                    .method(ElementMatchers.named("toString")).intercept(MethodCall.invoke(toString).onField("ident"))
                    .make()
                    .load(JackpotTrees.class.getClassLoader())
                    .getLoaded();
            baseClass2Impl.put(clazz, fake);
        }

        NEXT: for (Constructor c : fake.getDeclaredConstructors()) {
            if (c.getParameterCount() < requiredConstructor.length)
                continue;
            for (int e = 0; e < requiredConstructor.length; e++) {
                if (!c.getParameterTypes()[e].equals(requiredConstructor[e])) {
                    continue NEXT;
                }
            }
            java.util.List<Object> instances = new ArrayList<>();
            instances.addAll(Arrays.asList(params));
            for (int i = instances.size(); i < c.getParameterCount(); i++) {
                instances.add(null);
            }

            JCTree tree = (JCTree) c.newInstance(instances.toArray(new Object[0]));

            Field identField = fake.getDeclaredField("ident");

            identField.set(tree, ident);

            Field jcIdentField = fake.getDeclaredField("jcIdent");

            jcIdentField.set(tree, jcIdent);

            return clazz.cast(tree);
        }

        throw new IllegalStateException();
    } catch (IllegalAccessException | IllegalArgumentException | IllegalStateException | InstantiationException | NoSuchFieldException | NoSuchMethodException | SecurityException | InvocationTargetException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example 20
Project: Jupiter   File: Entity.java   View Source Code Vote up 4 votes
public static Entity createEntity(String name, FullChunk chunk, CompoundTag nbt, Object... args) {
    Entity entity = null;

    if (knownEntities.containsKey(name)) {
        Class<? extends Entity> clazz = knownEntities.get(name);

        if (clazz == null) {
            return null;
        }

        for (Constructor constructor : clazz.getConstructors()) {
            if (entity != null) {
                break;
            }

            if (constructor.getParameterCount() != (args == null ? 2 : args.length + 2)) {
                continue;
            }

            try {
                if (args == null || args.length == 0) {
                    entity = (Entity) constructor.newInstance(chunk, nbt);
                } else {
                    Object[] objects = new Object[args.length + 2];

                    objects[0] = chunk;
                    objects[1] = nbt;
                    System.arraycopy(args, 0, objects, 2, args.length);
                    entity = (Entity) constructor.newInstance(objects);

                }
            } catch (Exception e) {
                MainLogger.getLogger().logException(e);
            }

        }
    }

    //server.getAI().addAIQueue(entity);

    return entity;
}