List of usage examples for java.lang.reflect Constructor toGenericString
@Override
public String toGenericString()
From source file:Main.java
public static void main(String[] argv) throws Exception { Constructor[] constructors = ArrayList.class.getDeclaredConstructors(); for (int i = 0; i < constructors.length; i++) { Constructor c = constructors[i]; System.out.println(c.toGenericString()); }/* ww w . java 2 s. com*/ }
From source file:Charge.java
public static void main(String... args) { try {// w w w . j ava 2 s . co m Class<?> c = Charge.class; Constructor[] ctors = c.getDeclaredConstructors(); for (Constructor ctor : ctors) { out.format("Constructor: %s%n", ctor.toGenericString()); ctor.setAccessible(true); ctor.newInstance(); } // production code should handle these exceptions more gracefully } catch (InstantiationException x) { x.printStackTrace(); } catch (IllegalAccessException x) { x.printStackTrace(); } catch (InvocationTargetException x) { x.printStackTrace(); } }
From source file:EnumSpy.java
public static void main(String... args) { try {//from w w w. j av a 2 s. co m Class<?> c = Class.forName(args[0]); if (!c.isEnum()) { out.format("%s is not an enum type%n", c); return; } out.format("Class: %s%n", c); Field[] flds = c.getDeclaredFields(); List<Field> cst = new ArrayList<Field>(); // enum constants List<Field> mbr = new ArrayList<Field>(); // member fields for (Field f : flds) { if (f.isEnumConstant()) cst.add(f); else mbr.add(f); } if (!cst.isEmpty()) print(cst, "Constant"); if (!mbr.isEmpty()) print(mbr, "Field"); Constructor[] ctors = c.getDeclaredConstructors(); for (Constructor ctor : ctors) { out.format(fmt, "Constructor", ctor.toGenericString(), synthetic(ctor)); } Method[] mths = c.getDeclaredMethods(); for (Method m : mths) { out.format(fmt, "Method", m.toGenericString(), synthetic(m)); } // production code should handle this exception more gracefully } catch (ClassNotFoundException x) { x.printStackTrace(); } }
From source file:Main.java
public static void main(String... args) throws Exception { Class<?> c = Class.forName(args[0]); Constructor[] allConstructors = c.getDeclaredConstructors(); for (Constructor ctor : allConstructors) { int searchMod = modifierFromString(args[1]); int mods = accessModifiers(ctor.getModifiers()); if (searchMod == mods) { out.format("%s%n", ctor.toGenericString()); out.format(" [ synthetic=%-5b var_args=%-5b ]%n", ctor.isSynthetic(), ctor.isVarArgs()); }/*from w ww. j a va 2 s . c om*/ } }
From source file:ConstructorAccess.java
public static void main(String... args) { try {/*from www .j a v a2s . c om*/ Class<?> c = Class.forName(args[0]); Constructor[] allConstructors = c.getDeclaredConstructors(); for (Constructor ctor : allConstructors) { int searchMod = modifierFromString(args[1]); int mods = accessModifiers(ctor.getModifiers()); if (searchMod == mods) { out.format("%s%n", ctor.toGenericString()); out.format(" [ synthetic=%-5b var_args=%-5b ]%n", ctor.isSynthetic(), ctor.isVarArgs()); } } // production code should handle this exception more gracefully } catch (ClassNotFoundException x) { x.printStackTrace(); } }
From source file:ConstructorSift.java
public static void main(String... args) { try {//from w w w.ja v a 2s. co m Class<?> cArg = Class.forName(args[1]); Class<?> c = Class.forName(args[0]); Constructor[] allConstructors = c.getDeclaredConstructors(); for (Constructor ctor : allConstructors) { Class<?>[] pType = ctor.getParameterTypes(); for (int i = 0; i < pType.length; i++) { if (pType[i].equals(cArg)) { out.format("%s%n", ctor.toGenericString()); Type[] gpType = ctor.getGenericParameterTypes(); for (int j = 0; j < gpType.length; j++) { char ch = (pType[j].equals(cArg) ? '*' : ' '); out.format("%7c%s[%d]: %s%n", ch, "GenericParameterType", j, gpType[j]); } break; } } } // production code should handle this exception more gracefully } catch (ClassNotFoundException x) { x.printStackTrace(); } }
From source file:com.mani.cucumber.ReflectionUtils.java
public static <T> T newInstance(Class<T> clazz, Object... params) { Constructor<T> constructor = findConstructor(clazz, params); try {//w w w .ja v a2 s . c o m return constructor.newInstance(params); } catch (InstantiationException | IllegalAccessException ex) { throw new IllegalStateException("Could not invoke " + constructor.toGenericString(), ex); } catch (InvocationTargetException ex) { if (ex.getCause() instanceof RuntimeException) { throw (RuntimeException) ex.getCause(); } throw new IllegalStateException( "Unexpected checked exception thrown from " + constructor.toGenericString(), ex); } }
From source file:com.flipkart.polyguice.dropwiz.PolyguiceApp.java
private Object createResource(Class<?> cls, T config, Environment env) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { LOGGER.debug("creating object of type {}", cls); try {/*from w ww . j ava 2 s . c o m*/ Constructor<?> ctor = cls.getConstructor(Configuration.class, Environment.class); int mod = ctor.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod)) { LOGGER.debug("using ctor {}", ctor.toGenericString()); return ctor.newInstance(config, env); } } catch (NoSuchMethodException exep) { //NOOP, not even log } try { Constructor<?> ctor = cls.getConstructor(Environment.class, Configuration.class); int mod = ctor.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod)) { LOGGER.debug("using ctor {}", ctor.toGenericString()); return ctor.newInstance(env, config); } } catch (NoSuchMethodException exep) { //NOOP, not even log } try { Constructor<?> ctor = cls.getConstructor(Configuration.class); int mod = ctor.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod)) { LOGGER.debug("using ctor {}", ctor.toGenericString()); return ctor.newInstance(config); } } catch (NoSuchMethodException exep) { //NOOP, not even log } try { Constructor<?> ctor = cls.getConstructor(Environment.class); int mod = ctor.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod)) { LOGGER.debug("using ctor {}", ctor.toGenericString()); return ctor.newInstance(env); } } catch (NoSuchMethodException exep) { //NOOP, not even log } try { Constructor<?> ctor = cls.getConstructor(); int mod = ctor.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod)) { LOGGER.debug("using ctor {}", ctor.toGenericString()); return ctor.newInstance(); } } catch (NoSuchMethodException exep) { //NOOP, not even log } return null; }
From source file:net.sourceforge.cobertura.reporting.ComplexityCalculator.java
/** * Computes CCN for a method.//w w w .j a v a2 s .co m * * @param classData class data for the class which contains the method to compute CCN for * @param methodName the name of the method to compute CCN for * @param methodDescriptor the descriptor of the method to compute CCN for * @return CCN for the method * @throws NullPointerException if <code>classData</code> is <code>null</code> */ public int getCCNForMethod(ClassData classData, String methodName, String methodDescriptor) { if (!calculateMethodComplexity) { return 0; } Validate.notNull(classData, "classData must not be null"); Validate.notNull(methodName, "methodName must not be null"); Validate.notNull(methodDescriptor, "methodDescriptor must not be null"); int complexity = 0; List<FunctionMetric> methodMetrics = getFunctionMetricsForSingleFile(classData.getSourceFileName()); // golden method = method for which we need ccn String goldenMethodName = methodName; boolean isConstructor = false; if (goldenMethodName.equals("<init>")) { isConstructor = true; goldenMethodName = classData.getBaseName(); } // fully-qualify the method goldenMethodName = classData.getName() + "." + goldenMethodName; // replace nested class separator $ by . goldenMethodName = goldenMethodName.replaceAll(Pattern.quote("$"), "."); TraceSignatureVisitor v = new TraceSignatureVisitor(Opcodes.ACC_PUBLIC); SignatureReader r = new SignatureReader(methodDescriptor); r.accept(v); // for the scope of this method, signature = signature of the method excluding the method name String goldenSignature = v.getDeclaration(); // get parameter type list string which is enclosed by round brackets () goldenSignature = goldenSignature.substring(1, goldenSignature.length() - 1); // collect all the signatures with the same method name as golden method Map<String, Integer> candidateSignatureToCcn = new HashMap<String, Integer>(); for (FunctionMetric singleMethodMetrics : methodMetrics) { String candidateMethodName = singleMethodMetrics.name.substring(0, singleMethodMetrics.name.indexOf('(')); String candidateSignature = stripTypeParameters(singleMethodMetrics.name .substring(singleMethodMetrics.name.indexOf('(') + 1, singleMethodMetrics.name.length() - 1)); if (goldenMethodName.equals(candidateMethodName)) { candidateSignatureToCcn.put(candidateSignature, singleMethodMetrics.ccn); } } // if only one signature, no signature matching needed if (candidateSignatureToCcn.size() == 1) { return candidateSignatureToCcn.values().iterator().next(); } // else, do signature matching and find the best match // update golden signature using reflection if (!goldenSignature.isEmpty()) { try { String[] goldenParameterTypeStrings = goldenSignature.split(","); Class<?>[] goldenParameterTypes = new Class[goldenParameterTypeStrings.length]; for (int i = 0; i < goldenParameterTypeStrings.length; i++) { goldenParameterTypes[i] = ClassUtils.getClass(goldenParameterTypeStrings[i].trim(), false); } Class<?> klass = ClassUtils.getClass(classData.getName(), false); if (isConstructor) { Constructor<?> realMethod = klass.getDeclaredConstructor(goldenParameterTypes); goldenSignature = realMethod.toGenericString(); } else { Method realMethod = klass.getDeclaredMethod(methodName, goldenParameterTypes); goldenSignature = realMethod.toGenericString(); } // replace varargs ellipsis with array notation goldenSignature = goldenSignature.replaceAll("\\.\\.\\.", "[]"); // extract the parameter type list string goldenSignature = goldenSignature.substring(goldenSignature.indexOf("(") + 1, goldenSignature.length() - 1); // strip the type parameters to get raw types goldenSignature = stripTypeParameters(goldenSignature); } catch (Exception e) { logger.error("Error while getting method CC for " + goldenMethodName, e); return 0; } } // replace nested class separator $ by . goldenSignature = goldenSignature.replaceAll(Pattern.quote("$"), "."); // signature matching - due to loss of fully qualified parameter types from JavaCC, get ccn for the closest match double signatureMatchPercentTillNow = 0; for (Entry<String, Integer> candidateSignatureToCcnEntry : candidateSignatureToCcn.entrySet()) { String candidateSignature = candidateSignatureToCcnEntry.getKey(); double currentMatchPercent = matchSignatures(candidateSignature, goldenSignature); if (currentMatchPercent == 1) { return candidateSignatureToCcnEntry.getValue(); } if (currentMatchPercent > signatureMatchPercentTillNow) { complexity = candidateSignatureToCcnEntry.getValue(); signatureMatchPercentTillNow = currentMatchPercent; } } return complexity; }