Java Code Examples for java.lang.reflect.Constructor

The following are top voted examples for showing how to use java.lang.reflect.Constructor. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: lettuce   File: PrivateAccessorTest.java View source code Vote up 6 votes
@Test
public void testLettuceStrings() throws Exception {
    Constructor<?> constructor = theClass.getDeclaredConstructor();
    assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue();
    constructor.setAccessible(true);
    constructor.newInstance();
}
 
Example 2
Project: breakout   File: ObjectTreeTable.java View source code Vote up 6 votes
private static Constructor<?> findNullaryConstructor(Class<?> type) {
	for (Constructor<?> constructor : type.getDeclaredConstructors()) {
		if (constructor.getDeclaringClass().equals(type) && constructor.getParameterTypes().length == 0) {
			return constructor;
		}
	}
	return null;
}
 
Example 3
Project: p1keyboard   File: ImprovedBluetoothDevice.java View source code Vote up 6 votes
private static Constructor<?> getConstructor(Class<?> cls, Class<?>[] args) {
	try {
		Constructor<?> c = cls.getDeclaredConstructor(args);
		if (!c.isAccessible())
			c.setAccessible(true);
		return c;
	} catch (Exception ex) {
		return null;
	}
}
 
Example 4
Project: violetumleditor   File: ManiocFramework.java View source code Vote up 6 votes
/**
 * @param <T>
 * @param classType
 * @return the constructor annotated with \@Constructor or null if no
 *         one is found
 */
private <T> Constructor<T> getAnnotatedConstructor(Class<T> classType) {
        Constructor<T>[] constructors = (Constructor<T>[]) classType.getConstructors();
        List<Constructor<T>> result = new ArrayList<Constructor<T>>();
        for (Constructor<T> aConstructor : constructors) {
                int modifiers = aConstructor.getModifiers();
                if ((modifiers & Modifier.PUBLIC) != 0) {
                        continue;
                }
                Construct annotation = aConstructor.getAnnotation(Construct.class);
                if (annotation == null) {
                        continue;
                }
                result.add(aConstructor);
        }
        if (result.size() == 1) {
                return result.get(0);
        }
        if (result.size() > 1) {
                throw new ManiocException("BeanFactory cannot determine which constructor to use on " + classType.getName() + " because there's more than one constructor annotated with @" + Construct.class.getSimpleName());
        }
        return null;
}
 
Example 5
Project: avaje-ebeanorm   File: ReflectionBasedTypeBuilder.java View source code Vote up 6 votes
@SuppressWarnings({ "unchecked", "rawtypes" })
public ScalarType<?> buildScalarType(ImmutableMeta meta) {
    
    if (meta.isCompoundType()){
        throw new RuntimeException("Must be scalar");
    }
    
    Constructor<?> constructor = meta.getConstructor();
    
    Class<?> logicalType = constructor.getDeclaringClass();
    
    Method[] readers = meta.getReaders();
    Class<?> returnType = readers[0].getReturnType();
    
    ScalarType<?> scalarType = typeManager.recursiveCreateScalarTypes(returnType);
    
    ReflectionBasedScalarTypeConverter r = new ReflectionBasedScalarTypeConverter(constructor, readers[0]);
    
    return new ScalarTypeWrapper(logicalType, scalarType, r);
}
 
Example 6
Project: JerseyTest   File: ComponentConstructor.java View source code Vote up 6 votes
/**
 * Get the most suitable constructor. The constructor with the most
 * parameters and that has the most parameters associated with 
 * Injectable instances will be chosen.
 * 
 * @param <T> The type to construct.
 * @param c the class to instantiate.
 * @return a list of constructor and list of injectables for the constructor 
 *         parameters.
 */
private ConstructorInjectablePair<T> getConstructor() {
    if (c.getConstructors().length == 0)
        return null;
    
    SortedSet<ConstructorInjectablePair<T>> cs = new TreeSet<ConstructorInjectablePair<T>>(
            new ConstructorComparator());
    
    AnnotatedContext aoc = new AnnotatedContext();
    for (Constructor con : c.getConstructors()) {
        List<Injectable> is = new ArrayList<Injectable>();
        int ps = con.getParameterTypes().length;
        aoc.setAccessibleObject(con);
        for (int p = 0; p < ps; p++) {
            Type pgtype = con.getGenericParameterTypes()[p];
            Annotation[] as = con.getParameterAnnotations()[p];
            aoc.setAnnotations(as);
            Injectable i = null;
            for (Annotation a : as) {
                i = ipc.getInjectable(
                        a.annotationType(), aoc, a, pgtype, 
                        ComponentScope.UNDEFINED_SINGLETON);
            }
            is.add(i);
        }
        cs.add(new ConstructorInjectablePair<T>(con, is));
    }
            
    return cs.first();
}
 
Example 7
Project: xapi   File: GwtcEntryPointBuilder.java View source code Vote up 6 votes
public String formatInstanceProvider(Class<?> declaringClass) {
  String field = instanceProviders.get(declaringClass.getCanonicalName());
  if (field == null) {
    X_Log.trace(getClass(), "Generating instance field for ",declaringClass);
    field = X_Source.toStringEnclosed(declaringClass).replace('.', '_');
    field = Character.toLowerCase(field.charAt(0)) + field.substring(1);
    instanceProviders.put(declaringClass.getCanonicalName(), field);
    FieldBuffer buffer = cls.createField(declaringClass, field, Modifier.PRIVATE | Modifier.FINAL);
    StringBuilder b = new StringBuilder()
       .append("new ")
       .append(cls.addImport(declaringClass))
       .append("(");
    // Find the best constructor
    Constructor<?> winner = null;
    Constructor<?>[] ctors = declaringClass.getConstructors();
    search:
    for (int i = ctors.length; i --> 0;) {
      Constructor<?> ctor = ctors[i];
      if (ctor.getAnnotation(Inject.class) != null) {
        // Backup default, we'll accept @Inject constructors
        winner = ctor;
      }
      for (Annotation[] annos : ctor.getParameterAnnotations()) {
        for (Annotation anno : annos) {
          if (anno instanceof DefaultValue) {
            winner = ctor;
            break search;
          }
        }
      }
    }
    if (winner == null) {
      winner = GwtReflect.getPublicConstructor(declaringClass);
    }
    if (winner == null) {
      String error =
        "Cannot instantiate instance of "+declaringClass.getCanonicalName()+"; "
            + "as it does not have an any public constructors annotated with "
            + "@DefaultValue, or a zero-arg public constructor.";
      IllegalArgumentException exception = new IllegalArgumentException(error);
      X_Log.error(getClass(), error, exception);
      throw exception;
    }
    b.append(formatParameters(winner.getParameterTypes(), winner.getParameterAnnotations()));
    buffer.setInitializer(b+");");
  }
  return field;
}
 
Example 8
Project: JerseyTest   File: GuiceComponentProviderFactory.java View source code Vote up 6 votes
/**
 * Determine if a class is an implicit Guice component that can be
 * instatiated by Guice and the life-cycle managed by Jersey.
 * 
 * @param c the class.
 * @return true if the class is an implicit Guice component.
 */
public boolean isGuiceConstructorInjected(Class<?> c) {
    for (Constructor<?> con : c.getConstructors()) {
        if (con.isAnnotationPresent(Inject.class))
            return true;
    }

    return false;
}
 
Example 9
Project: many-ql   File: QLSReflection.java View source code Vote up 6 votes
private Object createNewInstance(Constructor constructor, List<Object> args)
        throws IllegalAccessException, InvocationTargetException, InstantiationException {
    if (constructor.isVarArgs()) {
        final Object[] newInstanceParametersUsingVarArgs = newInstanceParametersUsingVarArgs(args, constructor);
        return constructor.newInstance(newInstanceParametersUsingVarArgs);
    }
    return constructor.newInstance(args.toArray());
}
 
Example 10
Project: VarexJ   File: ConstructorTest.java View source code Vote up 6 votes
@Test
public void testAnnotations(){
  if (verifyNoPropertyViolation()) {
    try {
      Class<X> cls = X.class;
      Constructor<X> ctor = cls.getDeclaredConstructor(new Class<?>[] { String.class });

      Annotation[] ai = ctor.getDeclaredAnnotations();
      assertTrue("no declared ctor annotations found", ai.length == 1);
      
      assertTrue("wrong ctor annotation type", ai[0] instanceof A);
      System.out.printf("ctor annotation: " + ai[0]);
      
    } catch (Throwable t) {
      fail("ctor.getDeclaredAnnotations() failed: " + t);
    }
  }    
}
 
Example 11
Project: AdminCMD-Bukkit   File: MethodInfo.java View source code Vote up 5 votes
/**
 * Wraps a constructor as a method information object.
 *
 * @param constructor - the constructor to wrap.
 * @return A wrapped constructor.
 */
public static MethodInfo fromConstructor(final Constructor<?> constructor) {
        return new MethodInfo() {
                @Override
                public String getName() {
                        return constructor.getName();
                }

                @Override
                public Class<?>[] getParameterTypes() {
                        return constructor.getParameterTypes();
                }

                @Override
                public Class<?> getDeclaringClass() {
                        return constructor.getDeclaringClass();
                }

                @Override
                public Class<?> getReturnType() {
                        return Void.class;
                }

                @Override
                public int getModifiers() {
                        return constructor.getModifiers();
                }

                @Override
                public Class<?>[] getExceptionTypes() {
                        return constructor.getExceptionTypes();
                }

                @Override
                public TypeVariable<?>[] getTypeParameters() {
                        return constructor.getTypeParameters();
                }

                @Override
                public String toGenericString() {
                        return constructor.toGenericString();
                }

                @Override
                public String toString() {
                        return constructor.toString();
                }

                @Override
                public boolean isSynthetic() {
                        return constructor.isSynthetic();
                }

                @Override
                public int hashCode() {
                        return constructor.hashCode();
                }

                @Override
                public boolean isConstructor() {
                        return true;
                }

                public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
                        //only Java 8
                        return null;
                }

                public Annotation[] getAnnotations() {
                        //only Java 8
                        return null;
                }

                public Annotation[] getDeclaredAnnotations() {
                        //only Java 8
                        return null;
                }
        };
}