/** * Get an instance of {@link HiveRegister}. * * @param hiveRegisterType The name of a class that implements {@link HiveRegister}. * @param props A {@link State} object used to instantiate the {@link HiveRegister} object. */ public static HiveRegister get(String hiveRegisterType, State props, Optional<String> metastoreURI) { try { return (HiveRegister) ConstructorUtils.invokeConstructor(Class.forName(hiveRegisterType), props, metastoreURI); } catch (ReflectiveOperationException e) { throw Throwables.propagate(e); } }
/** * Convenience method on top of {@link ConstructorUtils#invokeConstructor(Class, Object[])} that returns a new * instance of the <code>cls</code> based on a constructor priority order. Each {@link List} in the * <code>constructorArgs</code> array contains the arguments for a constructor of <code>cls</code>. The first * constructor whose signature matches the argument types will be invoked. * * @param cls the class to be instantiated * @param constructorArgs An array of constructor argument list. Order defines the priority of a constructor. * @return * * @throws NoSuchMethodException if no constructor matched was found */ @SafeVarargs public static <T> T invokeFirstConstructor(Class<T> cls, List<Object>... constructorArgs) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { for (List<Object> args : constructorArgs) { Class<?>[] parameterTypes = new Class[args.size()]; for (int i = 0; i < args.size(); i++) { parameterTypes[i] = args.get(i).getClass(); } if (ConstructorUtils.getMatchingAccessibleConstructor(cls, parameterTypes) != null) { return ConstructorUtils.invokeConstructor(cls, args.toArray(new Object[args.size()])); } } throw new NoSuchMethodException("No accessible constructor found"); }
/** * <p>Finds a constructor given a class and signature, checking accessibility.</p> * * <p>This finds the constructor and ensures that it is accessible. * The constructor signature must match the parameter types exactly.</p> * * @param <T> the constructor type * @param cls the class to find a constructor for, not {@code null} * @param parameterTypes the array of parameter types, {@code null} treated as empty * @return the constructor, {@code null} if no matching accessible constructor found * @see Class#getConstructor * @see #getAccessibleConstructor(java.lang.reflect.Constructor) * @throws NullPointerException if {@code cls} is {@code null} */ public static <T> Constructor<T> getAccessibleConstructor(final Class<T> cls, final Class<?>... parameterTypes) { Validate.notNull(cls, "class cannot be null"); try { return getAccessibleConstructor(cls.getConstructor(parameterTypes)); } catch (final NoSuchMethodException e) { return null; } }
private void addServicesFromProperties(Properties properties) throws IllegalAccessException, InstantiationException, ClassNotFoundException, InvocationTargetException { if (properties.containsKey(APP_ADDITIONAL_SERVICES)) { for (String serviceClassName : new State(properties).getPropAsSet(APP_ADDITIONAL_SERVICES)) { Class<?> serviceClass = Class.forName(serviceClassName); if (Service.class.isAssignableFrom(serviceClass)) { Service service; Constructor<?> constructor = ConstructorUtils.getMatchingAccessibleConstructor(serviceClass, Properties.class); if (constructor != null) { service = (Service) constructor.newInstance(properties); } else { service = (Service) serviceClass.newInstance(); } addService(service); } else { throw new IllegalArgumentException(String.format("Class %s specified by %s does not implement %s", serviceClassName, APP_ADDITIONAL_SERVICES, Service.class.getSimpleName())); } } } }
/** * <p>Returns a new instance of the specified class inferring the right constructor * from the types of the arguments.</p> * * <p>This locates and calls a constructor. * The constructor signature must match the argument types exactly.</p> * * @param <T> the type to be constructed * @param cls the class to be constructed, not {@code null} * @param args the array of arguments, {@code null} treated as empty * @return new instance of {@code cls}, not {@code null} * * @throws NullPointerException if {@code cls} is {@code null} * @throws NoSuchMethodException if a matching constructor cannot be found * @throws IllegalAccessException if invocation is not permitted by security * @throws InvocationTargetException if an error occurs on invocation * @throws InstantiationException if an error occurs on instantiation * @see #invokeExactConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[]) */ public static <T> T invokeExactConstructor(final Class<T> cls, Object... args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { args = ArrayUtils.nullToEmpty(args); final Class<?> parameterTypes[] = ClassUtils.toClass(args); return invokeExactConstructor(cls, args, parameterTypes); }
args = ArrayUtils.nullToEmpty(args); parameterTypes = ArrayUtils.nullToEmpty(parameterTypes); final Constructor<T> ctor = getMatchingAccessibleConstructor(cls, parameterTypes); if (ctor == null) { throw new NoSuchMethodException(
@Test public void testInvokeExactConstructor() throws Exception { assertEquals("()", ConstructorUtils.invokeExactConstructor( TestBean.class, (Object[]) ArrayUtils.EMPTY_CLASS_ARRAY).toString()); assertEquals("()", ConstructorUtils.invokeExactConstructor( TestBean.class, (Object[]) null).toString()); assertEquals("(String)", ConstructorUtils.invokeExactConstructor( TestBean.class, "").toString()); assertEquals("(Object)", ConstructorUtils.invokeExactConstructor( TestBean.class, new Object()).toString()); assertEquals("(Integer)", ConstructorUtils.invokeExactConstructor( TestBean.class, NumberUtils.INTEGER_ONE).toString()); assertEquals("(double)", ConstructorUtils.invokeExactConstructor( TestBean.class, new Object[] { NumberUtils.DOUBLE_ONE }, new Class[] { Double.TYPE }).toString()); ConstructorUtils.invokeExactConstructor(TestBean.class, NumberUtils.BYTE_ONE); fail("should throw NoSuchMethodException"); ConstructorUtils.invokeExactConstructor(TestBean.class, NumberUtils.LONG_ONE); fail("should throw NoSuchMethodException"); ConstructorUtils.invokeExactConstructor(TestBean.class, Boolean.TRUE); fail("should throw NoSuchMethodException");
/** * 调用构造函数. */ public static <T> T invokeConstructor(final Class<T> cls, Object... args) { try { return ConstructorUtils.invokeConstructor(cls, args); } catch (Exception e) { throw ExceptionUtil.unwrapAndUnchecked(e); } }
/** * Returns a new instance of the <code>cls</code> based on a set of arguments. The method will search for a * constructor accepting the first k arguments in <code>args</code> for every k from args.length to 0, and will * invoke the first constructor found. * * For example, {@link #invokeLongestConstructor}(cls, myString, myInt) will first attempt to create an object with * of class <code>cls</code> with constructor <init>(String, int), if it fails it will attempt <init>(String), and * finally <init>(). * * @param cls the class to instantiate. * @param args the arguments to use for instantiation. * @throws ReflectiveOperationException */ public static <T> T invokeLongestConstructor(Class<T> cls, Object... args) throws ReflectiveOperationException { Class<?>[] parameterTypes = new Class[args.length]; for (int i = 0; i < args.length; i++) { parameterTypes[i] = args[i].getClass(); } for (int i = args.length; i >= 0; i--) { if (ConstructorUtils.getMatchingAccessibleConstructor(cls, Arrays.copyOfRange(parameterTypes, 0, i)) != null) { log.debug( String.format("Found accessible constructor for class %s with parameter types %s.", cls, Arrays.toString(Arrays.copyOfRange(parameterTypes, 0, i)))); return ConstructorUtils.invokeConstructor(cls, Arrays.copyOfRange(args, 0, i)); } } throw new NoSuchMethodException(String.format("No accessible constructor for class %s with parameters a subset of %s.", cls, Arrays.toString(parameterTypes))); }
private void expectMatchingAccessibleConstructorParameterTypes(final Class<?> cls, final Class<?>[] requestTypes, final Class<?>[] actualTypes) { final Constructor<?> c = ConstructorUtils.getMatchingAccessibleConstructor(cls, requestTypes); assertTrue(toString(c.getParameterTypes()) + " not equals " + toString(actualTypes), Arrays.equals(actualTypes, c .getParameterTypes())); }
args = ArrayUtils.nullToEmpty(args); parameterTypes = ArrayUtils.nullToEmpty(parameterTypes); final Constructor<T> ctor = getAccessibleConstructor(cls, parameterTypes); if (ctor == null) { throw new NoSuchMethodException(
/** * <p>Returns a new instance of the specified class inferring the right constructor * from the types of the arguments.</p> * * <p>This locates and calls a constructor. * The constructor signature must match the argument types exactly.</p> * * @param <T> the type to be constructed * @param cls the class to be constructed, not {@code null} * @param args the array of arguments, {@code null} treated as empty * @return new instance of {@code cls}, not {@code null} * * @throws NullPointerException if {@code cls} is {@code null} * @throws NoSuchMethodException if a matching constructor cannot be found * @throws IllegalAccessException if invocation is not permitted by security * @throws InvocationTargetException if an error occurs on invocation * @throws InstantiationException if an error occurs on instantiation * @see #invokeExactConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[]) */ public static <T> T invokeExactConstructor(final Class<T> cls, Object... args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { args = ArrayUtils.nullToEmpty(args); final Class<?> parameterTypes[] = ClassUtils.toClass(args); return invokeExactConstructor(cls, args, parameterTypes); }
@SuppressWarnings("unchecked") public static <K, S> KafkaSchemaRegistry<K, S> get(Properties props) { Preconditions.checkArgument(props.containsKey(KAFKA_SCHEMA_REGISTRY_CLASS), "Missing required property " + KAFKA_SCHEMA_REGISTRY_CLASS); Class<? extends KafkaSchemaRegistry<?, ?>> clazz; try { clazz = (Class<? extends KafkaSchemaRegistry<?, ?>>) Class.forName(props.getProperty(KAFKA_SCHEMA_REGISTRY_CLASS)); return (KafkaSchemaRegistry<K, S>) ConstructorUtils.invokeConstructor(clazz, props); } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) { log.error("Failed to instantiate " + KafkaSchemaRegistry.class, e); throw Throwables.propagate(e); } }
/** * Convenience method on top of {@link ConstructorUtils#invokeConstructor(Class, Object[])} that returns a new * instance of the <code>cls</code> based on a constructor priority order. Each {@link List} in the * <code>constructorArgs</code> array contains the arguments for a constructor of <code>cls</code>. The first * constructor whose signature matches the argument types will be invoked. * * @param cls the class to be instantiated * @param constructorArgs An array of constructor argument list. Order defines the priority of a constructor. * @return * * @throws NoSuchMethodException if no constructor matched was found */ @SafeVarargs public static <T> T invokeFirstConstructor(Class<T> cls, List<Object>... constructorArgs) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { for (List<Object> args : constructorArgs) { Class<?>[] parameterTypes = new Class[args.size()]; for (int i = 0; i < args.size(); i++) { parameterTypes[i] = args.get(i).getClass(); } if (ConstructorUtils.getMatchingAccessibleConstructor(cls, parameterTypes) != null) { return ConstructorUtils.invokeConstructor(cls, args.toArray(new Object[args.size()])); } } throw new NoSuchMethodException("No accessible constructor found"); }
/** * Instance factory calling a constructor with arguments. * @param cls The class to instantiate. * @param args The arguments. * @param <T> The instantiated type. * @return An instance factory to produce new instances of {@code cls}. */ public static <T> InstanceFactory<T> fromConstructor(Class<? extends T> cls, Object... args) { Class[] types = new Class[args.length]; for (int i = 0; i < args.length; i++) { types[i] = args[i].getClass(); } Constructor<? extends T> ctor = ConstructorUtils.getMatchingAccessibleConstructor(cls, types); if (ctor != null) { return new CtorInstanceFactory<T>(ctor, args); } else { throw new IllegalArgumentException("no matching constructor for " + cls); } }
@Test public void testGetAccessibleConstructor() throws Exception { assertNotNull(ConstructorUtils.getAccessibleConstructor(Object.class .getConstructor(ArrayUtils.EMPTY_CLASS_ARRAY))); assertNull(ConstructorUtils.getAccessibleConstructor(PrivateClass.class .getConstructor(ArrayUtils.EMPTY_CLASS_ARRAY))); assertNull(ConstructorUtils.getAccessibleConstructor(PrivateClass.PublicInnerClass.class)); }
/** * <p>Returns a new instance of the specified class inferring the right constructor * from the types of the arguments.</p> * * <p>This locates and calls a constructor. * The constructor signature must match the argument types exactly.</p> * * @param <T> the type to be constructed * @param cls the class to be constructed, not {@code null} * @param args the array of arguments, {@code null} treated as empty * @return new instance of {@code cls}, not {@code null} * * @throws NullPointerException if {@code cls} is {@code null} * @throws NoSuchMethodException if a matching constructor cannot be found * @throws IllegalAccessException if invocation is not permitted by security * @throws InvocationTargetException if an error occurs on invocation * @throws InstantiationException if an error occurs on instantiation * @see #invokeExactConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[]) */ public static <T> T invokeExactConstructor(final Class<T> cls, Object... args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { args = ArrayUtils.nullToEmpty(args); final Class<?> parameterTypes[] = ClassUtils.toClass(args); return invokeExactConstructor(cls, args, parameterTypes); }
protected HiveRegistrationUnitComparator<?> getPartitionComparator(HivePartition existingPartition, HivePartition newPartition) { try { Class<?> clazz = Class.forName(this.props.getProp(HIVE_PARTITION_COMPARATOR_TYPE, DEFAULT_HIVE_PARTITION_COMPARATOR_TYPE)); return (HiveRegistrationUnitComparator<?>) ConstructorUtils.invokeConstructor(clazz, existingPartition, newPartition); } catch (ReflectiveOperationException e) { log.error("Unable to instantiate Hive partition comparator", e); throw Throwables.propagate(e); } }
/** * Convenience method on top of {@link ConstructorUtils#invokeConstructor(Class, Object[])} that returns a new * instance of the <code>cls</code> based on a constructor priority order. Each {@link List} in the * <code>constructorArgs</code> array contains the arguments for a constructor of <code>cls</code>. The first * constructor whose signature matches the argument types will be invoked. * * @param cls the class to be instantiated * @param constructorArgs An array of constructor argument list. Order defines the priority of a constructor. * @return * * @throws NoSuchMethodException if no constructor matched was found */ @SafeVarargs public static <T> T invokeFirstConstructor(Class<T> cls, List<Object>... constructorArgs) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { for (List<Object> args : constructorArgs) { Class<?>[] parameterTypes = new Class[args.size()]; for (int i = 0; i < args.size(); i++) { parameterTypes[i] = args.get(i).getClass(); } if (ConstructorUtils.getMatchingAccessibleConstructor(cls, parameterTypes) != null) { return ConstructorUtils.invokeConstructor(cls, args.toArray(new Object[args.size()])); } } throw new NoSuchMethodException("No accessible constructor found"); }
public Deserializer create(final T dict) { try { final Constructor<Deserializer> constructor = ConstructorUtils.getMatchingAccessibleConstructor(clazz, dict.getClass()); return constructor.newInstance(dict); } catch(InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new FactoryException(e.getMessage(), e); } }