/** * Create a default object of the given type. Prefers constructors with as few arguments as * possible. Creates an empty proxy for interfaces. * * @param type type to instantiate * @return default instance * @throws Exception if the default instance could not be created */ private static Object instantiateType(Class<?> type) throws Exception { if (type.isPrimitive()) return Defaults.defaultValue(type); else if (type == Void.class) return null; else if (type.isArray()) return Array.newInstance(type, 0); else if (type.isInterface()) return Proxy.newProxyInstance( type.getClassLoader(), new Class[] {type}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return null; } }); // Take a constructor with as few params as possible Constructor constructor = type.getDeclaredConstructors()[0]; for (Constructor<?> c : type.getDeclaredConstructors()) { if (c.getParameterTypes().length < constructor.getParameterTypes().length) constructor = c; } Object[] params = new Object[constructor.getParameterTypes().length]; for (int i = 0; i < constructor.getParameterTypes().length; i++) { params[i] = instantiateType(constructor.getParameterTypes()[i]); } return constructor.newInstance(params); }
private static <T> void checkIsValidPartial(Class<T> cls) { checkArgument(isAbstract(cls.getModifiers()), "Partial class must be abstract"); checkArgument( cls.getDeclaredConstructors().length == 1, "Partial class %s must have exactly one constructor (found %s)", cls, cls.getDeclaredConstructors().length); Constructor<?> constructor = cls.getDeclaredConstructors()[0]; checkArgument( !isPrivate(constructor.getModifiers()), "Partial class %s must have a package-visible constructor", cls); }
private void validateClass(Class<?> source, ValidationProblemCollector problems) { int modifiers = source.getModifiers(); if (Modifier.isInterface(modifiers)) { problems.add("Must be a class, not an interface"); } if (source.getEnclosingClass() != null) { if (Modifier.isStatic(modifiers)) { if (Modifier.isPrivate(modifiers)) { problems.add("Class cannot be private"); } } else { problems.add("Enclosed classes must be static and non private"); } } Constructor<?>[] constructors = source.getDeclaredConstructors(); for (Constructor<?> constructor : constructors) { if (constructor.getParameterTypes().length > 0) { problems.add("Cannot declare a constructor that takes arguments"); break; } } Field[] fields = source.getDeclaredFields(); for (Field field : fields) { int fieldModifiers = field.getModifiers(); if (!field.isSynthetic() && !(Modifier.isStatic(fieldModifiers) && Modifier.isFinal(fieldModifiers))) { problems.add(field, "Fields must be static final."); } } }
/** * This class returns a ClassStatsHolder object which holds statistics about a class * * @param classname * @return */ private ClassStatsHolder getStatistics(String classname) { ClassStatsHolder ret = null; try { // get methods, constructors etc Class theClass = Class.forName(classname); Integer numFields = theClass.getDeclaredFields().length; Method[] methods = theClass.getDeclaredMethods(); Integer members = (theClass.getDeclaredFields().length) + methods.length; Constructor[] constructors = theClass.getDeclaredConstructors(); // create ararys of method names an number of parameters String[] totalMethods = new String[methods.length]; Integer[] paramaters = new Integer[methods.length]; for (int i = 0; i < methods.length; i++) { totalMethods[i] = methods[i].getName(); paramaters[i] = methods[i].getParameterTypes().length; } ret = new ClassStatsHolder( classname, totalMethods, paramaters, members, constructors, numFields); } catch (ClassNotFoundException e) { e.printStackTrace(); // will never be reached if recursion is done } return ret; }
private static void print(Class<?> clazz) { if (WarpCommons.debugMode()) { System.out.println(); System.out.println("Class: " + clazz.getName()); System.out.println( "SuperClass: " + clazz.getSuperclass() + " " + clazz.getSuperclass().hashCode()); System.out.println("Interfaces: " + Arrays.asList(clazz.getInterfaces())); System.out.println("Fields"); for (Field field : clazz.getDeclaredFields()) { printAnnotation(field); System.out.println("\t" + field); } System.out.println("Constructors"); for (Constructor<?> constructor : clazz.getDeclaredConstructors()) { printAnnotation(constructor); System.out.println("\t" + constructor); } System.out.println("Methods"); for (Method method : clazz.getDeclaredMethods()) { printAnnotation(method); System.out.println("\t" + method); } } }
private static <T> T getInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { Constructor<T> constructor = (Constructor<T>) clazz.getDeclaredConstructors()[0]; constructor.setAccessible(true); return constructor.newInstance(null); }
private void generateConstructors(JavaClass jClass, String superClassName) { for (Constructor baseCtor : _cl.getDeclaredConstructors()) { if (Modifier.isPrivate(baseCtor.getModifiers())) continue; generateConstructor(jClass, superClassName, baseCtor); } }
private static Constructor<?> getConstructor(Class<?> cl, Class<?>[] paramTypes) { for (Constructor<?> ctor : cl.getDeclaredConstructors()) { if (isMatch(ctor.getParameterTypes(), paramTypes)) return ctor; } throw new IllegalStateException("No matching constructor found for " + cl); }
public Factory(Class<T> type) { this.type = type; Constructor<?>[] all = type.getDeclaredConstructors(); this.takeOne = searchConstructor(all, 1); this.takeTwo = searchConstructor(all, 2); this.takeThree = searchConstructor(all, 3); }
private static <T> T getInstanceFromNonDefaultConstructor(Class<T> targetClass) { Constructor<?>[] constructors = targetClass.getDeclaredConstructors(); constructors = DatabaseFileLookupTest.orderByParamCount(constructors); for (Constructor<?> constructor : constructors) { constructor.setAccessible(true); Class<?>[] parameterTypes = constructor.getParameterTypes(); try { /** Trying to invoke constructor with <code>null</code> values. */ @SuppressWarnings("unchecked") T instance = (T) constructor.newInstance(new Object[parameterTypes.length]); return instance; } catch (Exception ignored) { } /** Creating proper instances for the parameter types. */ Object[] arguments = DatabaseFileLookupTest.createArguments(parameterTypes, targetClass); if (arguments == null) { continue; } try { @SuppressWarnings("unchecked") T instance = (T) constructor.newInstance(arguments); return instance; } catch (Exception ignored) { } } return null; }
protected void _addConstructorMixIns(Class<?> mixin) { MemberKey[] ctorKeys = null; int ctorCount = (_constructors == null) ? 0 : _constructors.size(); for (Constructor<?> ctor : mixin.getDeclaredConstructors()) { switch (ctor.getParameterTypes().length) { case 0: if (_defaultConstructor != null) { _addMixOvers(ctor, _defaultConstructor, false); } break; default: if (ctorKeys == null) { ctorKeys = new MemberKey[ctorCount]; for (int i = 0; i < ctorCount; ++i) { ctorKeys[i] = new MemberKey(_constructors.get(i).getAnnotated()); } } MemberKey key = new MemberKey(ctor); for (int i = 0; i < ctorCount; ++i) { if (!key.equals(ctorKeys[i])) { continue; } _addMixOvers(ctor, _constructors.get(i), true); break; } } } }
/** * This method creates the constraint instance. * * @param constraintStructure the constraint's structure (bConstraint clss in blender 2.49). * @param ownerOMA the old memory address of the constraint's owner * @param influenceIpo the ipo curve of the influence factor * @param blenderContext the blender context * @throws BlenderFileException this exception is thrown when the blender file is somehow * corrupted */ protected Constraint createConstraint( Structure constraintStructure, Long ownerOMA, Ipo influenceIpo, BlenderContext blenderContext) throws BlenderFileException { String constraintClassName = this.getConstraintClassName(constraintStructure, blenderContext); Class<? extends Constraint> constraintClass = constraintClasses.get(constraintClassName); if (constraintClass != null) { try { return (Constraint) constraintClass.getDeclaredConstructors()[0].newInstance( constraintStructure, ownerOMA, influenceIpo, blenderContext); } catch (IllegalArgumentException e) { throw new BlenderFileException(e.getLocalizedMessage(), e); } catch (SecurityException e) { throw new BlenderFileException(e.getLocalizedMessage(), e); } catch (InstantiationException e) { throw new BlenderFileException(e.getLocalizedMessage(), e); } catch (IllegalAccessException e) { throw new BlenderFileException(e.getLocalizedMessage(), e); } catch (InvocationTargetException e) { throw new BlenderFileException(e.getLocalizedMessage(), e); } } else { throw new BlenderFileException("Unknown constraint type: " + constraintClassName); } }
@Override public Class<?> classForName(String name) { try { // Class<?> clazz = getClassLoader().loadClass(name); // Class<?> clazz = getClass().getClassLoader().loadClass(name); Class<?> clazz = bundle.loadClass(name); // if the class relies on optional dependencies that are not present // then a CNFE can be thrown later in the deployment process when the // Introspector is inspecting the class. We call getMethods, getFields // and getConstructors now over the whole type heirachey to force // these errors to occur early. // NOTE it is still possible for a CNFE to be thrown at runtime if // a class has methods that refer to classes that are not present in // their bytecode, this only checks for classes that form part of the // class schema that are not present Class<?> obj = clazz; while (obj != null && obj != Object.class) { obj.getDeclaredConstructors(); obj.getDeclaredFields(); obj.getDeclaredMethods(); obj = obj.getSuperclass(); } return clazz; } catch (ClassNotFoundException e) { throw new ResourceLoadingException(e); } catch (NoClassDefFoundError e) { throw new ResourceLoadingException(e); } }
/** * @param declaringClass * @return the ordered list of declared constructors for the given class */ public static List<Constructor<?>> getDeclaredConstructors(Class<?> declaringClass) { Preconditions.checkNotNull(declaringClass); List<Constructor<?>> declaredConstructors = Arrays.asList(declaringClass.getDeclaredConstructors()); Collections.sort(declaredConstructors, CONSTRUCTOR_COMPARATOR_INSTANCE); return declaredConstructors; }
/* (non-Javadoc) * @see rezeptManager.entity.DataEntity#createNextChild(common.IEntity, java.lang.Class) */ @SuppressWarnings("rawtypes") @Override public IEntity createNextChild(IEntity parent, Class c) throws Exception { if (c == null) { return null; } int maxChildNr = 0; for (LinkedEntity child : getChildListForClass(c).values()) { if (child.getNr() > maxChildNr) { maxChildNr = child.getNr(); } } Integer newChildNr = maxChildNr; newChildNr++; if (this.getChildListForClass(c).size() >= getMaxChildListSize(c)) { return null; } else { Constructor[] ctors = c.getDeclaredConstructors(); Constructor ctor = null; for (int i = 0; i < ctors.length; i++) { ctor = ctors[i]; Type[] genericParameterTypes = ctor.getGenericParameterTypes(); if (genericParameterTypes.length == 2 && genericParameterTypes[0].equals(IEntity.class) && genericParameterTypes[1].equals(IEntity.class)) break; } IEntity child = (IEntity) (ctor != null ? ctor.newInstance(this, new DataEntity(newChildNr)) : null); return child; } }
public Constructor[] getAllConstructorsFromClass(Class c) { Constructor[] cList; cList = c.getDeclaredConstructors(); return cList; }
private void checkCompoundIds(Class<?> javaClass) throws IOException { String javaClassName = javaClass.getCanonicalName(); PsiClass psiClass = myJavaPsiFacade.findClass( javaClassName, GlobalSearchScope.moduleWithLibrariesScope(myModule)); assertNotNull(psiClass); for (java.lang.reflect.Method javaMethod : javaClass.getDeclaredMethods()) { Method method = new Method( Type.getType(javaClass).getInternalName(), javaMethod.getName(), Type.getMethodDescriptor(javaMethod)); boolean noKey = javaMethod.getAnnotation(ExpectNoPsiKey.class) != null; PsiMethod psiMethod = psiClass.findMethodsByName(javaMethod.getName(), false)[0]; checkCompoundId(method, psiMethod, noKey); } for (Constructor<?> constructor : javaClass.getDeclaredConstructors()) { Method method = new Method( Type.getType(javaClass).getInternalName(), "<init>", Type.getConstructorDescriptor(constructor)); boolean noKey = constructor.getAnnotation(ExpectNoPsiKey.class) != null; PsiMethod[] constructors = psiClass.getConstructors(); PsiMethod psiMethod = constructors[0]; checkCompoundId(method, psiMethod, noKey); } }
/** * Finds constructors of the specified access level in the supplied class. * * @param c the class to search in * @param level the access level to look for * @param sb the StringBuffer where the results should be added */ private static void listConstructors(Class c, int level, StringBuffer sb) { Constructor[] constrs = c.getDeclaredConstructors(); Constructor constructor; Class[] exceptions; StringBuffer cons; for (int index = 0; index < constrs.length; index++) { constructor = constrs[index]; if (isAccessible(constructor.getModifiers(), level)) { cons = new StringBuffer(100); cons.append(printConstructor(constructor.getName(), constructor.getParameterTypes())); // Add exceptions exceptions = constructor.getExceptionTypes(); if (exceptions.length > 0) { cons.append(printExceptions(exceptions)); } else { cons.append(NIL); } cons.append(END_PAREN); if (sb.toString().lastIndexOf(cons.toString()) == -1) { sb.append(cons); } } } }
public void apply() throws IllegalAccessException, InvocationTargetException, InstantiationException { if (type.isEnum()) { for (T instance : type.getEnumConstants()) { assertThat( instance.toString(), is( type.getCanonicalName().substring(type.getPackage().getName().length() + 1) + "." + ((Enum<?>) instance).name())); } return; } for (Constructor<?> constructor : type.getDeclaredConstructors()) { if (constructor.isSynthetic() && skipSynthetic) { continue; } constructor.setAccessible(true); Class<?>[] parameterTypes = constructor.getParameterTypes(); Object[] actualArguments = new Object[parameterTypes.length]; Object[] otherArguments = new Object[parameterTypes.length]; int index = 0; for (Class<?> parameterType : parameterTypes) { putInstance(parameterType, actualArguments, otherArguments, index++); } int testIndex = 0; @SuppressWarnings("unchecked") T instance = (T) constructor.newInstance(actualArguments); assertThat(instance, is(instance)); assertThat(instance, not(is((Object) null))); assertThat(instance, not(is(new Object()))); Object similarInstance = constructor.newInstance(actualArguments); assertThat(instance.hashCode(), is(similarInstance.hashCode())); assertThat(instance, is(similarInstance)); if (skipToString) { assertThat(instance.toString(), notNullValue()); } else if (optionalToStringRegex == null) { checkString(instance); } else { assertThat(instance.toString(), new RegexMatcher(optionalToStringRegex)); } for (Object otherArgument : otherArguments) { Object[] compareArguments = new Object[actualArguments.length]; int argumentIndex = 0; for (Object actualArgument : actualArguments) { if (argumentIndex == testIndex) { compareArguments[argumentIndex] = otherArgument; } else { compareArguments[argumentIndex] = actualArgument; } argumentIndex++; } Object unlikeInstance = constructor.newInstance(compareArguments); assertThat(instance.hashCode(), not(is(unlikeInstance))); assertThat(instance, not(is(unlikeInstance))); testIndex++; } } }
@SuppressWarnings("unchecked") // assuming only one constructor. // If need to support more this code should change private static Constructor<? extends UIQueryBase> findQueryConstructor( Class<? extends UIQueryBase> type) { Constructor<?>[] constructors = type.getDeclaredConstructors(); return (Constructor<? extends UIQueryBase>) constructors[0]; }
/** * Gets all constructors of this class * * @return an array with all the constructors in this class */ public RefConstructor[] getConstructors() { Constructor<?>[] constructors = clazz.getDeclaredConstructors(); RefConstructor[] refConstructors = new RefConstructor[constructors.length]; for (int i = 0; i < constructors.length; i++) { refConstructors[i] = new RefConstructor(constructors[i]); } return refConstructors; }
private void verifyExternalClass(final Class clazz) { // don't recommended to instantiate the class doing clazz.newInstance(). clazz.getDeclaredConstructors(); clazz.getDeclaredFields(); clazz.getDeclaredMethods(); clazz.getDeclaredClasses(); clazz.getDeclaredAnnotations(); }
private void checkDefaultConstructor(Class<?> clazz) { for (Constructor constructor : clazz.getDeclaredConstructors()) { if (constructor.getParameterTypes().length == 0) { return; } } throw new IllegalArgumentException("The class can't be serialized"); }
@Override public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException { // Quick check on the concurrent map first, with minimal locking. Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass); if (candidateConstructors == null) { synchronized (this.candidateConstructorsCache) { candidateConstructors = this.candidateConstructorsCache.get(beanClass); if (candidateConstructors == null) { Constructor<?>[] rawCandidates = beanClass.getDeclaredConstructors(); List<Constructor<?>> candidates = new ArrayList<Constructor<?>>(rawCandidates.length); Constructor<?> requiredConstructor = null; Constructor<?> defaultConstructor = null; for (Constructor<?> candidate : rawCandidates) { Annotation annotation = findAutowiredAnnotation(candidate); if (annotation != null) { if (requiredConstructor != null) { throw new BeanCreationException( "Invalid autowire-marked constructor: " + candidate + ". Found another constructor with 'required' Autowired annotation: " + requiredConstructor); } if (candidate.getParameterTypes().length == 0) { throw new IllegalStateException( "Autowired annotation requires at least one argument: " + candidate); } boolean required = determineRequiredStatus(annotation); if (required) { if (!candidates.isEmpty()) { throw new BeanCreationException( "Invalid autowire-marked constructors: " + candidates + ". Found another constructor with 'required' Autowired annotation: " + requiredConstructor); } requiredConstructor = candidate; } candidates.add(candidate); } else if (candidate.getParameterTypes().length == 0) { defaultConstructor = candidate; } } if (!candidates.isEmpty()) { // Add default constructor to list of optional constructors, as fallback. if (requiredConstructor == null && defaultConstructor != null) { candidates.add(defaultConstructor); } candidateConstructors = candidates.toArray(new Constructor<?>[candidates.size()]); } else { candidateConstructors = new Constructor<?>[0]; } this.candidateConstructorsCache.put(beanClass, candidateConstructors); } } } return (candidateConstructors.length > 0 ? candidateConstructors : null); }
/** * すべてのメンバを表示する * * @param Class<?> c メンバを表示したいクラス型オブジェクト */ public static void printAllMembers(Class<?> c) { System.out.println("クラス: "); System.out.println(c); System.out.println("フィールド: "); Field[] declaredfields = c.getDeclaredFields(); Field[] fields = c.getFields(); ArrayList<Field> fieldList = new ArrayList<Field>(fields.length); for (int i = 0; i < fields.length; i++) { fieldList.add(fields[i]); } for (int i = 0; i < declaredfields.length; i++) { if (!fieldList.contains(declaredfields[i])) { fieldList.add(declaredfields[i]); } } Field[] allFields = new Field[fieldList.size()]; for (int i = 0; i < allFields.length; i++) { allFields[i] = fieldList.get(i); } printMembers(allFields); System.out.println("コンストラクタ: "); Constructor[] declaredconstructors = c.getDeclaredConstructors(); Constructor[] constructors = c.getConstructors(); ArrayList<Constructor> constructorList = new ArrayList<Constructor>(constructors.length); for (int i = 0; i < constructors.length; i++) { constructorList.add(constructors[i]); } for (int i = 0; i < declaredconstructors.length; i++) { if (!constructorList.contains(declaredconstructors[i])) { constructorList.add(declaredconstructors[i]); } } Constructor[] allConstructors = new Constructor[constructorList.size()]; for (int i = 0; i < allConstructors.length; i++) { allConstructors[i] = constructorList.get(i); } printMembers(allConstructors); System.out.println("メソッド: "); Method[] declaredmethods = c.getDeclaredMethods(); Method[] methods = c.getMethods(); ArrayList<Method> methodList = new ArrayList<Method>(methods.length); for (int i = 0; i < methods.length; i++) { methodList.add(methods[i]); } for (int i = 0; i < declaredmethods.length; i++) { if (!methodList.contains(declaredmethods[i])) { methodList.add(declaredmethods[i]); } } Method[] allMethods = new Method[methodList.size()]; for (int i = 0; i < allMethods.length; i++) { allMethods[i] = methodList.get(i); } printMembers(allMethods); }
@Test public void testConstructor() throws Exception { Class<HMAC> c = HMAC.class; assertEquals(1, c.getDeclaredConstructors().length); Constructor<HMAC> constructor = c.getDeclaredConstructor(); assertTrue(Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true); constructor.newInstance(); }
public static boolean isValidConstructor(Class<?> type) { for (Constructor<?> ctor : type.getDeclaredConstructors()) { if (ctor.getParameterTypes().length == 0) return true; if (ctor.isAnnotationPresent(Inject.class)) return true; } return false; }
/** * Get all the declared constructors on the class hierarchy. This <b>will</b> return overridden * constructors. * * @param clazz The class to search * @return the set of all declared constructors or an empty set if there are none */ public static Set<Constructor<?>> getAllDeclaredConstructors(Class<?> clazz) { HashSet<Constructor<?>> constructors = new HashSet<Constructor<?>>(); for (Class<?> c = clazz; c != null && c != Object.class; c = c.getSuperclass()) { for (Constructor<?> constructor : c.getDeclaredConstructors()) { constructors.add(constructor); } } return constructors; }
public static void initializeClass(final Class<?> theClass) { final Constructor<?>[] cons = theClass.getDeclaredConstructors(); if (cons != null && cons.length > 0 && cons[0] != null) { final String[] strs = new String[256]; try { cons[0].newInstance((Object[]) strs); } catch (Exception ex) { } } }
@SuppressWarnings({"unchecked", "rawtypes"}) private static <T> Constructor<T> findMatchingConstructor(Class<T> clazz, Object[] args) { for (Constructor constructor : clazz.getDeclaredConstructors()) { // cannot use <?> or <T> due to JDK 5/6 incompatibility if (matches(constructor.getParameterTypes(), args)) { return constructor; } } return null; }