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

The following examples show how to use java.lang.reflect.Constructor#getParameterTypes() . 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: ReflectUtils.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: ReflectUtils.java    From dubbox with Apache License 2.0 6 votes vote down vote up
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;
  }
 
Example 3
Source File: DbxClientV2Test.java    From dropbox-sdk-java with MIT License 6 votes vote down vote up
private FileMetadata constructFileMetadate() throws Exception {
    Class builderClass = FileMetadata.Builder.class;
    Constructor constructor = builderClass.getDeclaredConstructors()[0];
    constructor.setAccessible(true);

    List<Object> arguments = new ArrayList<Object>(Arrays.asList(
            "bar.txt",
            "id:1HkLjqifwMAAAAAAAAAAAQ",
            new Date(1456169040985L),
            new Date(1456169040985L),
            "2e0c38735597",
            2091603
    ));

    // hack for internal version of SDK
    if (constructor.getParameterTypes().length > 6) {
        arguments.addAll(Arrays.asList("20MB", "text.png", "text/plain"));
    }

    FileMetadata.Builder builder = (FileMetadata.Builder) constructor.newInstance(arguments.toArray());
    return builder.build();
}
 
Example 4
Source File: ThrowableAttributeConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private Throwable getThrowable(final Class<Throwable> throwableClass, final Throwable cause) {
    try {
        @SuppressWarnings("unchecked")
        final
        Constructor<Throwable>[] constructors = (Constructor<Throwable>[]) throwableClass.getConstructors();
        for (final Constructor<Throwable> constructor : constructors) {
            final Class<?>[] parameterTypes = constructor.getParameterTypes();
            if (parameterTypes.length == 1 && Throwable.class.isAssignableFrom(parameterTypes[0])) {
                return constructor.newInstance(cause);
            }
        }
        return null;
    } catch (final Exception e) {
        return null;
    }
}
 
Example 5
Source File: ConstructorResultColumnProcessor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static Constructor resolveConstructor(Class targetClass, List<Type> types) {
	for ( Constructor constructor : targetClass.getConstructors() ) {
		final Class[] argumentTypes = constructor.getParameterTypes();
		if ( argumentTypes.length != types.size() ) {
			continue;
		}

		boolean allMatched = true;
		for ( int i = 0; i < argumentTypes.length; i++ ) {
			if ( ! areAssignmentCompatible( argumentTypes[i], types.get( i ).getReturnedClass() ) ) {
				allMatched = false;
				break;
			}
		}
		if ( !allMatched ) {
			continue;
		}

		return constructor;
	}

	throw new IllegalArgumentException( "Could not locate appropriate constructor on class : " + targetClass.getName() );
}
 
Example 6
Source File: JavaAdapterBytecodeGenerator.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private void generateConstructors(final Constructor<?> ctor) {
    if(classOverride) {
        // Generate a constructor that just delegates to ctor. This is used with class-level overrides, when we want
        // to create instances without further per-instance overrides.
        generateDelegatingConstructor(ctor);
    } else {
        // Generate a constructor that delegates to ctor, but takes an additional ScriptObject parameter at the
        // beginning of its parameter list.
        generateOverridingConstructor(ctor, false);

        if (samName != null) {
            if (!autoConvertibleFromFunction && ctor.getParameterTypes().length == 0) {
                // If the original type only has a single abstract method name, as well as a default ctor, then it can
                // be automatically converted from JS function.
                autoConvertibleFromFunction = true;
            }
            // If all our abstract methods have a single name, generate an additional constructor, one that takes a
            // ScriptFunction as its first parameter and assigns it as the implementation for all abstract methods.
            generateOverridingConstructor(ctor, true);
        }
    }
}
 
Example 7
Source File: InternalContext.java    From gadtry with Apache License 2.0 6 votes vote down vote up
private <T> T newInstance(Class<T> driver)
        throws Exception
{
    final Constructor<T> constructor = selectConstructor(driver);
    constructor.setAccessible(true);

    List<Object> builder = new ArrayList<>();
    for (Class<?> argType : constructor.getParameterTypes()) {
        checkState(argType != driver && check(argType), "Found a circular dependency involving " + driver + ", and circular dependencies are disabled.");

        Object value = getInstance(argType);
        checkState(value != null, String.format("Could not find a suitable constructor in [%s]. Classes must have either one (and only one) constructor annotated with @Autowired or a constructor that is not private(and only one).", argType));
        builder.add(value);
    }

    T instance = constructor.newInstance(builder.toArray());
    return buildAnnotationFields(driver, instance);
}
 
Example 8
Source File: LinearModelFactory.java    From sgdtk with Apache License 2.0 6 votes vote down vote up
private Constructor negotiateConstructor() throws NoSuchMethodException
{
    try
    {
        Class classV = Class.forName(className);
        Constructor[] allConstructors = classV.getDeclaredConstructors();
        for (Constructor ctor : allConstructors)
        {
            Class<?>[] pType = ctor.getParameterTypes();
            if (pType.length == 1 && pType[0].toGenericString().equals("int"))
            {
                return ctor;
            }
        }
    }
    catch (ClassNotFoundException classNoEx)
    {
        throw new NoSuchMethodException(classNoEx.getMessage());
    }
    throw new NoSuchMethodException("No constructor found!");
}
 
Example 9
Source File: ClassUtil.java    From android-common with Apache License 2.0 6 votes vote down vote up
/**
 * 根据类获取对象:不再必须一个无参构造
 *
 * @param claxx
 * @return
 * @throws Exception
 */
public static <T> T newInstance(Class<T> claxx) throws Exception {
    Constructor<?>[] cons = claxx.getDeclaredConstructors();
    for (Constructor<?> c : cons) {
        Class[] cls = c.getParameterTypes();
        if (cls.length == 0) {
            c.setAccessible(true);
            return (T) c.newInstance();
        } else {
            Object[] objs = new Object[cls.length];
            for (int i = 0; i < cls.length; i++) {
                objs[i] = getDefaultPrimiticeValue(cls[i]);
            }
            c.setAccessible(true);
            return (T) c.newInstance(objs);
        }
    }
    return null;
}
 
Example 10
Source File: BeanInjector.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private Object createObject( Class<?> clazz, Object root ) throws KettleException {
  try {
    // Object can be inner of metadata class. In this case constructor will require parameter
    for ( Constructor<?> c : clazz.getConstructors() ) {
      if ( c.getParameterTypes().length == 0 ) {
        return clazz.newInstance();
      } else if ( c.getParameterTypes().length == 1 && c.getParameterTypes()[0].isAssignableFrom( info.clazz ) ) {
        return c.newInstance( root );
      }
    }
  } catch ( Throwable ex ) {
    throw new KettleException( "Can't create object " + clazz, ex );
  }
  throw new KettleException( "Constructor not found for " + clazz );
}
 
Example 11
Source File: RegistryEntityDriverFactory.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private <D> Constructor<D> getConstructor(Class<? extends D> driverClass) {
    for (Constructor constructor : driverClass.getConstructors()) {
        if (constructor.getParameterTypes().length == 2) {
            return constructor;
        }
    }

    //TODO:
    throw new RuntimeException(String.format("Class [%s] has no constructor with 2 arguments",driverClass.getName()));
}
 
Example 12
Source File: Utils.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiate a class instance from a given className with three args
 * @param className
 * @param arg1
 * @param arg2
 * @param arg3
 * @param <T>
 * @return
 * @throws ReflectiveOperationException
 */
public static <T> T getObj(String className, Object arg1, Object arg2, Object arg3)
    throws ReflectiveOperationException {
  for (Constructor<?> ctor : Class.forName(className).getDeclaredConstructors()) {
    Class<?>[] paramTypes = ctor.getParameterTypes();
    if (paramTypes.length == 3 && checkAssignable(paramTypes[0], arg1) && checkAssignable(paramTypes[1], arg2)
        && checkAssignable(paramTypes[2], arg3)) {
      return (T) ctor.newInstance(arg1, arg2, arg3);
    }
  }
  throw buildNoConstructorException(className, arg1, arg2, arg3);
}
 
Example 13
Source File: JavaTypeFactory.java    From hypergraphdb with Apache License 2.0 5 votes vote down vote up
public static Constructor<?> findDefaultConstructor(Class<?> c)
{
       for (Constructor<?> con : c.getDeclaredConstructors())
           if (con.getParameterTypes().length == 0)
               return con;
       return null;	    
}
 
Example 14
Source File: Asm.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
public static Type[] getArgumentTypes(Constructor<?> constructor) {
    Class[] var1 = constructor.getParameterTypes();
    Type[] var2 = new Type[var1.length];

    for(int var3 = var1.length - 1; var3 >= 0; --var3) {
        var2[var3] = Type.getType(var1[var3]);
    }

    return var2;
}
 
Example 15
Source File: DrillHttpSecurityHandlerProvider.java    From Bats with Apache License 2.0 4 votes vote down vote up
public DrillHttpSecurityHandlerProvider(DrillConfig config, DrillbitContext drillContext)
    throws DrillbitStartupException {

  Preconditions.checkState(config.getBoolean(ExecConstants.USER_AUTHENTICATION_ENABLED));
  final Set<String> configuredMechanisms = getHttpAuthMechanisms(config);

  final ScanResult scan = drillContext.getClasspathScan();
  final Collection<Class<? extends DrillHttpConstraintSecurityHandler>> factoryImpls =
      scan.getImplementations(DrillHttpConstraintSecurityHandler.class);
  logger.debug("Found DrillHttpConstraintSecurityHandler implementations: {}", factoryImpls);

  for (final Class<? extends DrillHttpConstraintSecurityHandler> clazz : factoryImpls) {

    // If all the configured mechanisms handler is added then break out of this loop
    if (configuredMechanisms.isEmpty()) {
      break;
    }

    Constructor<? extends DrillHttpConstraintSecurityHandler> validConstructor = null;
    for (final Constructor<?> c : clazz.getConstructors()) {
      final Class<?>[] params = c.getParameterTypes();
      if (params.length == 0) {
        validConstructor = (Constructor<? extends DrillHttpConstraintSecurityHandler>) c; // unchecked
        break;
      }
    }

    if (validConstructor == null) {
      logger.warn("Skipping DrillHttpConstraintSecurityHandler class {}. It must implement at least one" +
          " constructor with signature [{}()]", clazz.getCanonicalName(), clazz.getName());
      continue;
    }

    try {
      final DrillHttpConstraintSecurityHandler instance = validConstructor.newInstance();
      if (configuredMechanisms.remove(instance.getImplName())) {
        instance.doSetup(drillContext);
        securityHandlers.put(instance.getImplName(), instance);
      }
    } catch (IllegalArgumentException | ReflectiveOperationException | DrillException e) {
      logger.warn(String.format("Failed to create DrillHttpConstraintSecurityHandler of type '%s'",
          clazz.getCanonicalName()), e);
    }
  }

  if (securityHandlers.size() == 0) {
    throw new DrillbitStartupException("Authentication is enabled for WebServer but none of the security mechanism " +
        "was configured properly. Please verify the configurations and try again.");
  }

  logger.info("Configure auth mechanisms for WebServer are: {}", securityHandlers.keySet());
}
 
Example 16
Source File: ClassReflectionIndex.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@SuppressWarnings({"unchecked"})
ClassReflectionIndex(final Class<?> indexedClass, final DeploymentReflectionIndex deploymentReflectionIndex) {
    this.deploymentReflectionIndex = deploymentReflectionIndex;
    this.indexedClass = indexedClass;
    // -- fields --
    final Field[] declaredFields = indexedClass.getDeclaredFields();
    final Map<String, Field> fields = new HashMap<String, Field>();
    for (Field field : declaredFields) {
        field.setAccessible(true);
        fields.put(field.getName(), field);
    }
    this.fields = fields;
    // -- methods --
    final Method[] declaredMethods = indexedClass.getDeclaredMethods();
    final Map<String, Map<ParamList, Map<Class<?>, Method>>> methods = new HashMap<String, Map<ParamList, Map<Class<?>, Method>>>();
    final Map<String, Map<ParamNameList, Map<String, Method>>> methodsByTypeName = new HashMap<String, Map<ParamNameList, Map<String, Method>>>();
    for (Method method : declaredMethods) {
        // Ignore setting the accessible flag as Object.class comes from the java.base module in Java 9+. Really the
        // only method that causes a warning and eventual failure is finalize(), but there's no reason for the
        // overhead of the change.
        if (method.getDeclaringClass() != Object.class) {
            method.setAccessible(true);
        }
        addMethod(methods, method);
        addMethodByTypeName(methodsByTypeName, method);
    }

    this.methods = methods;
    this.methodsByTypeName = methodsByTypeName;
    // -- constructors --
    final Constructor<?>[] declaredConstructors = (Constructor<?>[]) indexedClass.getDeclaredConstructors();
    final Map<ParamNameList, Constructor<?>> constructorsByTypeName = new HashMap<ParamNameList, Constructor<?>>();
    final Map<ParamList, Constructor<?>> constructors = new HashMap<ParamList, Constructor<?>>();
    for (Constructor<?> constructor : declaredConstructors) {
        constructor.setAccessible(true);
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        constructors.put(createParamList(parameterTypes), constructor);
        constructorsByTypeName.put(createParamNameList(parameterTypes), constructor);
    }
    this.constructorsByTypeName = constructorsByTypeName;
    this.constructors = constructors;
}
 
Example 17
Source File: MemberUtils.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
private Executable(final Constructor<?> constructor) {
    parameterTypes = constructor.getParameterTypes();
    isVarArgs = constructor.isVarArgs();
}
 
Example 18
Source File: ClassGeneratorVault.java    From baratine with GNU General Public License v2.0 4 votes vote down vote up
ClassGeneratorVault(Class<T> type,
                         ClassLoader loader)
{
  Objects.requireNonNull(type);
  
  _type = type;
  _classLoader = loader;
  
  if (! Vault.class.isAssignableFrom(_type)) {
    throw new IllegalArgumentException(L.l("{0} is an invalid Resource",
                                           _type));
  }

  /*
  if (! api.isInterface()) {
    throw new IllegalStateException(L.l("invalid interface {0}", api));
  }
  */
  ArrayList<Class<?>> apiList = new ArrayList<>();
  
  Constructor<?> zeroCtor = null;

  if (! type.isInterface()) {
    for (Constructor<?> ctorItem : type.getDeclaredConstructors()) {
      if (ctorItem.getParameterTypes().length == 0) {
        zeroCtor = ctorItem;
        break;
      }
    }

    // String typeClassName = cl.getName().replace('.', '/');

    if (zeroCtor == null) {
      ArrayList<Class<?>> interfaces = getInterfaces(type);

      throw new ConfigException(L.l("'{0}' does not have a zero-arg public or protected constructor.  Scope adapter components need a zero-arg constructor, e.g. @RequestScoped stored in @ApplicationScoped.",
                                    type.getName()));
    }
    else {
      apiList.add(type);
    }
  }
  else {
    apiList.add(type);
  }
}
 
Example 19
Source File: ModelRuleInspector.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Validates that the given class is effectively static and has no instance state.
 *
 * @param source the class the validate
 */
public void validate(Class<?> source) throws InvalidModelRuleDeclarationException {

    // TODO - exceptions thrown here should point to some extensive documentation on the concept of class rule sources

    int modifiers = source.getModifiers();

    if (Modifier.isInterface(modifiers)) {
        throw invalid(source, "must be a class, not an interface");
    }
    if (Modifier.isAbstract(modifiers)) {
        throw invalid(source, "class cannot be abstract");
    }

    if (source.getEnclosingClass() != null) {
        if (Modifier.isStatic(modifiers)) {
            if (Modifier.isPrivate(modifiers)) {
                throw invalid(source, "class cannot be private");
            }
        } else {
            throw invalid(source, "enclosed classes must be static and non private");
        }
    }

    Class<?> superclass = source.getSuperclass();
    if (!superclass.equals(Object.class)) {
        throw invalid(source, "cannot have superclass");
    }

    Constructor<?>[] constructors = source.getDeclaredConstructors();
    if (constructors.length > 1) {
        throw invalid(source, "cannot have more than one constructor");
    }

    Constructor<?> constructor = constructors[0];
    if (constructor.getParameterTypes().length > 0) {
        throw invalid(source, "constructor cannot take any arguments");
    }

    Field[] fields = source.getDeclaredFields();
    for (Field field : fields) {
        int fieldModifiers = field.getModifiers();
        if (!field.isSynthetic() && !(Modifier.isStatic(fieldModifiers) && Modifier.isFinal(fieldModifiers))) {
            throw invalid(source, "field " + field.getName() + " is not static final");
        }
    }

}
 
Example 20
Source File: Builder.java    From dubbox-hystrix with Apache License 2.0 votes vote down vote up
public int compare(Constructor o1, Constructor o2){ return o1.getParameterTypes().length - o2.getParameterTypes().length; }