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

The following examples show how to use java.lang.reflect.Constructor#getParameterCount() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Package.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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
Source File: ReflectionUtils.java    From embedded-database-spring-test with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T invokeConstructor(Class<?> targetClass, Object... args) {
    Assert.notNull(targetClass, "Target class must not be null");

    try {
        for (Constructor<?> constructor : targetClass.getDeclaredConstructors()) {
            if (constructor.getParameterCount() != args.length) {
                continue;
            }
            Class<?>[] parameterTypes = constructor.getParameterTypes();
            boolean parametersMatches = IntStream.range(0, args.length)
                    .allMatch(i -> ClassUtils.isAssignableValue(parameterTypes[i], args[i]));
            if (parametersMatches) {
                org.springframework.util.ReflectionUtils.makeAccessible(constructor);
                return (T) constructor.newInstance(args);
            }
        }
        throw new IllegalArgumentException(String.format("Could not find constructor on %s", targetClass));
    } catch (Exception ex) {
        org.springframework.util.ReflectionUtils.handleReflectionException(ex);
        throw new IllegalStateException("Should never get here");
    }
}
 
Example 3
Source File: ActionEventTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected RemoteEntityEvent<?> createRemoteEvent(final Action baseEntity,
        final Class<? extends RemoteEntityEvent<?>> eventType) {

    Constructor<?> constructor = null;
    for (final Constructor<?> constructors : eventType.getDeclaredConstructors()) {
        if (constructors.getParameterCount() == 4) {
            constructor = constructors;
        }
    }

    if (constructor == null) {
        throw new IllegalArgumentException("No suitable constructor foundes");
    }

    try {
        return (RemoteEntityEvent<?>) constructor.newInstance(baseEntity, 1L, 2L, "Node");
    } catch (final ReflectiveOperationException e) {
        fail("Exception should not happen " + e.getMessage());
    }
    return null;
}
 
Example 4
Source File: PublicSuper.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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
Source File: ObjectContainer.java    From flink-statefun with Apache License 2.0 6 votes vote down vote up
private static Constructor<?> findConstructorForInjection(Class<?> type) {
  Constructor<?>[] constructors = type.getDeclaredConstructors();
  Constructor<?> defaultCont = null;
  for (Constructor<?> constructor : constructors) {
    Annotation annotation = constructor.getAnnotation(Inject.class);
    if (annotation != null) {
      return constructor;
    }
    if (constructor.getParameterCount() == 0) {
      defaultCont = constructor;
    }
  }
  if (defaultCont != null) {
    return defaultCont;
  }
  throw new RuntimeException("not injectable type " + type);
}
 
Example 6
Source File: AbstractBeanDefinition.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Return the resolved autowire code,
 * (resolving AUTOWIRE_AUTODETECT to AUTOWIRE_CONSTRUCTOR or AUTOWIRE_BY_TYPE).
 * @see #AUTOWIRE_AUTODETECT
 * @see #AUTOWIRE_CONSTRUCTOR
 * @see #AUTOWIRE_BY_TYPE
 */
public int getResolvedAutowireMode() {
	if (this.autowireMode == AUTOWIRE_AUTODETECT) {
		// Work out whether to apply setter autowiring or constructor autowiring.
		// If it has a no-arg constructor it's deemed to be setter autowiring,
		// otherwise we'll try constructor autowiring.
		Constructor<?>[] constructors = getBeanClass().getConstructors();
		for (Constructor<?> constructor : constructors) {
			if (constructor.getParameterCount() == 0) {
				return AUTOWIRE_BY_TYPE;
			}
		}
		return AUTOWIRE_CONSTRUCTOR;
	}
	else {
		return this.autowireMode;
	}
}
 
Example 7
Source File: ObjectContainer.java    From stateful-functions with Apache License 2.0 6 votes vote down vote up
private static Constructor<?> findConstructorForInjection(Class<?> type) {
  Constructor<?>[] constructors = type.getDeclaredConstructors();
  Constructor<?> defaultCont = null;
  for (Constructor<?> constructor : constructors) {
    Annotation annotation = constructor.getAnnotation(Inject.class);
    if (annotation != null) {
      return constructor;
    }
    if (constructor.getParameterCount() == 0) {
      defaultCont = constructor;
    }
  }
  if (defaultCont != null) {
    return defaultCont;
  }
  throw new RuntimeException("not injectable type " + type);
}
 
Example 8
Source File: App.java    From java-slack-sdk with MIT License 6 votes vote down vote up
private String getEventTypeAndSubtype(Class<? extends Event> clazz) {
    String cached = eventTypeAndSubtypeValues.get(clazz);
    if (cached != null) {
        return cached;
    } else {
        for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
            if (constructor.getParameterCount() == 0) {
                try {
                    Event event = (Event) constructor.newInstance();
                    String typeAndSubtype = event.getType();
                    if (event.getSubtype() != null) {
                        typeAndSubtype = event.getType() + ":" + event.getSubtype();
                    }
                    eventTypeAndSubtypeValues.put(clazz, typeAndSubtype);
                    return typeAndSubtype;
                } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
                    log.error("Unexpectedly failed to load event type for the class {}", clazz.getCanonicalName());
                    break;
                }
            }
        }
    }
    return null;
}
 
Example 9
Source File: SQLExceptionConverterFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static SQLExceptionConverter constructConverter(String converterClassName, ViolatedConstraintNameExtracter violatedConstraintNameExtracter) {
	try {
		LOG.tracev( "Attempting to construct instance of specified SQLExceptionConverter [{0}]", converterClassName );
		final Class converterClass = ReflectHelper.classForName( converterClassName );

		// First, try to find a matching constructor accepting a ViolatedConstraintNameExtracter param...
		final Constructor[] ctors = converterClass.getDeclaredConstructors();
		for ( Constructor ctor : ctors ) {
			if ( ctor.getParameterTypes() != null && ctor.getParameterCount() == 1 ) {
				if ( ViolatedConstraintNameExtracter.class.isAssignableFrom( ctor.getParameterTypes()[0] ) ) {
					try {
						return (SQLExceptionConverter) ctor.newInstance( violatedConstraintNameExtracter );
					}
					catch (Throwable ignore) {
						// eat it and try next
					}
				}
			}
		}

		// Otherwise, try to use the no-arg constructor
		return (SQLExceptionConverter) converterClass.newInstance();

	}
	catch (Throwable t) {
		LOG.unableToConstructSqlExceptionConverter( t );
	}

	return null;
}
 
Example 10
Source File: Entity.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
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 11
Source File: InternalContext.java    From gadtry with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> Constructor<T> selectConstructor(Class<T> driver)
{
    Constructor<T>[] constructors;
    if (Creator.class.isAssignableFrom(driver)) {
        constructors = (Constructor<T>[]) driver.getDeclaredConstructors();
    }
    else {
        if (driver.isInterface() || Modifier.isAbstract(driver.getModifiers())) {
            throw new IllegalStateException(driver + " cannot be instantiated, No binding entity class");
        }
        constructors = (Constructor<T>[]) driver.getConstructors(); //public
    }

    Constructor<T> noParameter = null;
    for (Constructor<T> constructor : constructors) {
        Autowired autowired = constructor.getAnnotation(Autowired.class);
        if (autowired != null) {
            return constructor;
        }
        if (constructor.getParameterCount() == 0) {
            //find 'no parameter' Constructor, using class.newInstance()";
            noParameter = constructor;
        }
    }

    if (noParameter != null) {
        return noParameter;
    }

    checkState(constructors.length == 1, String.format("%s has multiple public constructors, please ensure that there is only one", driver));
    return constructors[0];
}
 
Example 12
Source File: MethodCallMetadataValidator.java    From yare with MIT License 5 votes vote down vote up
private static boolean hasDefaultPublicConstructor(Class<?> clazz) {
    Constructor<?>[] constructors = clazz.getConstructors();
    for (Constructor<?> constructor : constructors) {
        if (constructor.getParameterCount() == 0) {
            return true;
        }
    }
    return false;
}
 
Example 13
Source File: ConstructorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_getParameterCount() throws Exception {
    Class[] expectedParameters = new Class[0];
    Constructor<?> constructor = ConstructorTestHelper.class.getConstructor(expectedParameters);
    assertEquals(0, constructor.getParameterCount());

    expectedParameters = new Class[] { Object.class };
    constructor = ConstructorTestHelper.class.getConstructor(expectedParameters);
    int count = constructor.getParameterCount();
    assertEquals(1, count);
}
 
Example 14
Source File: MethodsProcessor.java    From Summer with MIT License 5 votes vote down vote up
private static Object newClass(Class clazz){

        try {
            for (Constructor<?> c : clazz.getDeclaredConstructors()) {
                c.setAccessible(true);
                if (c.getParameterCount() == 0) {
                    return c.newInstance();
                }
            }
        }catch (Exception e){
            LOGGER.error(e.getMessage());
        }
        return null;

    }
 
Example 15
Source File: MethodIdentifier.java    From typesafeconfig-guice with Apache License 2.0 5 votes vote down vote up
public boolean matchesConstructor(Class<?> clazz, Constructor<?> constructor, ScanResult scanResult) {
    if (clazz.getCanonicalName().equals(className) && methodName.equals("<init>") && constructor.getParameterCount() == parameterTypeSignature.length)
    {
        boolean paramsMatch = true;
        for (int i = 0; i < parameterTypeSignature.length; i++) {
            paramsMatch = paramsMatch && parameterTypeSignature[i].instantiate(scanResult) == constructor.getParameters()[i].getType();
        }
        return paramsMatch;
    }
    return false;
}
 
Example 16
Source File: BlockEntity.java    From Jupiter with GNU General Public License v3.0 4 votes vote down vote up
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 17
Source File: BlockEntity.java    From BukkitPE with GNU General Public License v3.0 4 votes vote down vote up
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 18
Source File: Entity.java    From Jupiter with GNU General Public License v3.0 4 votes vote down vote up
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;
}
 
Example 19
Source File: BinderToConstructor.java    From Diorite with MIT License 4 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
BinderToConstructor(Controller controller, Class<? extends T> type, Constructor<?> constructor)
{
    this.controller = controller;
    Constructor<? extends T> constructor1 = (Constructor<? extends T>) constructor;
    constructor1.setAccessible(true);

    MethodDescription.ForLoadedConstructor constructorDesc = new MethodDescription.ForLoadedConstructor(constructor);
    Map<Class<? extends Annotation>, ? extends Annotation> scopeMap = controller.extractRawScopeAnnotations(constructorDesc);
    Map<Class<? extends Annotation>, ? extends Annotation> qualifierMap = controller.extractRawQualifierAnnotations(constructorDesc);

    int parameterCount = constructor.getParameterCount();
    ArrayList<ControllerInjectValueData<?>> params = new ArrayList<>(parameterCount);
    ParameterList<ParameterDescription.InDefinedShape> parameters = constructorDesc.getParameters();
    for (int i = 0; i < parameterCount; i++)
    {
        ParameterDescription.InDefinedShape param = parameters.get(i);
        ControllerInjectValueData<Object> value = controller.createValue(- 1, constructorDesc.getDeclaringType(), param.getType(), param,
                                                                         param.getName(), scopeMap, qualifierMap);
        params.add(value);
    }
    this.params = List.of(params.toArray(new ControllerInjectValueData[parameterCount]));

    this.constructor = $this ->
    {
        Object[] args = new Object[parameterCount];
        for (int i = 0; i < parameterCount; i++)
        {
            args[i] = this.params.get(i).tryToGet($this);
        }
        try
        {
            return constructor1.newInstance(args);
        }
        catch (InstantiationException | IllegalAccessException | InvocationTargetException e)
        {
            throw new RuntimeException("Can't bind value to " + constructor1.getDeclaringClass().getName() + " constructor. " +
                                       Arrays.toString(constructor1.getParameterTypes()), e);
        }
    };
}
 
Example 20
Source File: ObjectInitializer.java    From java-slack-sdk with MIT License 4 votes vote down vote up
public static <T> T initProperties(T obj) {
    Field currentField = null;
    try {
        for (Field field : obj.getClass().getDeclaredFields()) {
            currentField = field;
            if (Modifier.isStatic(field.getModifiers()) ||
                    Modifier.isFinal(field.getModifiers()) ||
                    Modifier.isAbstract(field.getModifiers())) {
                continue;
            }
            field.setAccessible(true);

            Class<?> type = field.getType();
            if (field.getName().startsWith("initial")) {
                // set as null
            } else if (field.getName().startsWith("image")) {
                // set as null
            } else if (field.getName().equals("fallback")) {
                // set as null
            } else if (field.getName().equals("url")) {
                field.set(obj, "https://www.example.com/test-url");
            } else if (field.getName().equals("actionId") && type.equals(String.class)) {
                field.set(obj, "action-" + System.currentTimeMillis() + "-" + RANDOM.nextInt(1024));
            } else if (field.getName().equals("blockId") && type.equals(String.class)) {
                field.set(obj, "block-" + System.currentTimeMillis() + "-" + RANDOM.nextInt(1024));
            } else if (field.getName().equals("style") && type.equals(String.class)) {
                field.set(obj, "primary");
            } else if (field.getName().equals("initialDate") && type.equals(String.class)) {
                field.set(obj, "2020-03-11");
            } else if (type.equals(String.class)) {
                field.set(obj, "str");
            } else if (type.equals(Integer.class)) {
                field.set(obj, 123);
            } else if (type.equals(Long.class)) {
                field.set(obj, 123L);
            } else if (type.equals(Double.class)) {
                field.set(obj, 12.3D);
            } else if (type.equals(Boolean.class)) {
                field.set(obj, false);
            } else if (type.equals(List.class)) {
                List listObj = (List) field.get(obj);
                if (listObj != null) {
                    for (Object o : listObj) {
                        initProperties(o);
                    }
                } else {
                    log.info("null List object detected {} in {}", field.getName(), obj.getClass().getSimpleName());
                }
            } else {
                if (field.get(obj) != null) {
                    initProperties(field.get(obj));
                    continue;
                }
                for (Constructor<?> constructor : type.getDeclaredConstructors()) {
                    if (constructor.getParameterCount() == 0) {
                        Object childObj = constructor.newInstance();
                        initProperties(childObj);
                        field.set(obj, childObj);
                        continue;
                    }
                }
                log.info("Skipped a field which doesn't have non arg constructor: {} in {}", field.getName(), obj.getClass().getSimpleName());
            }
        }
        return obj;

    } catch (Exception e) {
        // because this method can be used in initializer code
        String message = "Failed to instantiate " + currentField.getType().getName() + " " + currentField.getName()
                + " in " + obj.getClass().getSimpleName();
        throw new RuntimeException(message, e);
    }
}