List of usage examples for org.apache.commons.lang3 ClassUtils getClass
public static Class<?> getClass(final String className, final boolean initialize) throws ClassNotFoundException
From source file:com.github.dozermapper.core.util.DefaultClassLoader.java
public Class<?> loadClass(String className) { Class<?> result = null; try {/*from w w w . j av a2 s . co m*/ result = ClassUtils.getClass(classLoader, className); } catch (ClassNotFoundException e) { try { result = ClassUtils.getClass(Thread.currentThread().getContextClassLoader(), className); } catch (ClassNotFoundException cnfe) { MappingUtils.throwMappingException(e); } } return result; }
From source file:com.bitranger.parknshop.common.recommend.util.io.CustomClassLoaderObjectInputStream.java
@Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { if (classLoader == null) { return super.resolveClass(desc); } else {/* ww w . j a v a2s .c o m*/ String name = desc.getName(); logger.debug("resolving class {}", name); return ClassUtils.getClass(classLoader, name); } }
From source file:edu.umich.flowfence.sandbox.ResolvedQM.java
private Class<?>[] classNamesToClasses(List<String> classNames, ClassLoader loader) throws Exception { Class<?>[] classes = new Class<?>[classNames.size()]; for (int i = 0; i < classNames.size(); i++) { classes[i] = ClassUtils.getClass(loader, classNames.get(i)); }/*from w w w. j ava 2 s.c o m*/ return classes; }
From source file:hu.bme.mit.sette.common.model.snippet.Snippet.java
/** * Parses a method which should be considered in coverage. * * @param includedClass/*from ww w.j a v a2 s.com*/ * the Java class of the method * @param includedMethodString * the string representing the included method * @param v * a {@link MethodValidator} * @param classLoader * the class loader for loading snippet project classes */ private void parseIncludedMethod(final Class<?> includedClass, final String includedMethodString, final MethodValidator v, final ClassLoader classLoader) { Matcher matcher = Snippet.METHOD_STRING_PATTERN.matcher(includedMethodString); if (!matcher.matches() || matcher.groupCount() != 2) { // invalid method string String message = String.format("The included method string must match " + "the required format.\n" + "(includedMethodString: [%s])", includedMethodString); v.addException(message); } else { // valid method string String includedMethodName = matcher.group(1).trim(); String[] paramTypeStrings = StringUtils.split(matcher.group(2), ','); Class<?>[] paramTypes = new Class<?>[paramTypeStrings.length]; boolean isConstructor = includedMethodName.equals(includedClass.getSimpleName()); boolean shouldAdd = true; // only add if there was no problem with // the parameters // check parameter types for (int i = 0; i < paramTypes.length; i++) { String parameterTypeString = paramTypeStrings[i].trim(); if (StringUtils.isBlank(parameterTypeString)) { // blank parameter type string String message = String.format("The included method string has " + "a blank parameter type.\n" + "(includedMethodString: [%s])\n" + "(index: [%d])", includedMethodString, i); v.addException(message); shouldAdd = false; } else { try { paramTypes[i] = ClassUtils.getClass(classLoader, parameterTypeString); } catch (ClassNotFoundException e) { // parameter type was not found String format = "The parameter type in " + "the included method string " + "could not have been loaded.\n" + "(includedMethodString: [%s])\n" + "(index: [%d])"; String message = String.format(format, includedMethodString, i); v.addException(message); shouldAdd = false; } } } if (shouldAdd) { // get included method object if (isConstructor) { try { // only search declared constructors Constructor<?> found = includedClass.getDeclaredConstructor(paramTypes); addIncludedConstructor(found, v); } catch (NoSuchMethodException e) { String format = "Included constructor cannot be found " + "(it must be declared in the class)\n" + "(includedClass: [%s])\n" + "(includedMethodString: [%s])"; String message = String.format(format, includedClass, includedMethodString); v.addException(message); } } else { try { // only search declared methods Method found = includedClass.getDeclaredMethod(includedMethodName, paramTypes); addIncludedMethod(found, v); } catch (NoSuchMethodException e) { String format = "Included method cannot be found " + "(it must be declared in the class)\n" + "(includedClass: [%s])\n" + "(includedMethodString: [%s])"; String message = String.format(format, includedClass, includedMethodString); v.addException(message, e); } } } } }
From source file:net.sourceforge.cobertura.reporting.ComplexityCalculator.java
/** * Computes CCN for a method.// w w w . ja v a 2 s . c om * * @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; }
From source file:net.sourceforge.pmd.lang.java.typeresolution.TypeHelper.java
private static Class<?> loadClass(final ClassLoader nullableClassLoader, final String clazzName) { try {/*from w w w .j a v a 2 s . c o m*/ ClassLoader classLoader = nullableClassLoader; if (classLoader == null) { // Using the system classloader then classLoader = ClassLoader.getSystemClassLoader(); } // If the requested type is in the classpath, using the same classloader should work return ClassUtils.getClass(classLoader, clazzName); } catch (ClassNotFoundException ignored) { // The requested type is not on the auxclasspath. This might happen, if the type node // is probed for a specific type (e.g. is is a JUnit5 Test Annotation class). // Failing to resolve clazzName does not necessarily indicate an incomplete auxclasspath. } catch (final LinkageError expected) { // We found the class but it's invalid / incomplete. This may be an incomplete auxclasspath // if it was a NoClassDefFoundError. TODO : Report it? } return null; }
From source file:org.dozer.util.DefaultClassLoader.java
public Class<?> loadClass(String className) { Class<?> result = null; try {/* w ww . ja v a2 s . c o m*/ result = ClassUtils.getClass(classLoader, className); } catch (ClassNotFoundException e) { MappingUtils.throwMappingException(e); } return result; }
From source file:org.grouplens.grapht.util.ClassProxy.java
/** * Resolve a class proxy to a class.//from w w w . j av a 2 s . c o m * @return The class represented by this proxy. * @throws ClassNotFoundException if the class represented by this proxy cannot be found. */ public Class<?> resolve() throws ClassNotFoundException { WeakReference<Class<?>> ref = theClass; Class<?> cls = ref == null ? null : ref.get(); if (cls == null) { if (className.equals("void")) { // special case cls = Void.TYPE; } else { cls = ClassUtils.getClass(classLoader, className); } long check = checksumClass(cls); if (!isSerializationPermissive() && checksum != check) { throw new ClassNotFoundException("checksum mismatch for " + cls.getName()); } else { if (checksum != check) { logger.warn("checksum mismatch for {}", cls); } theClass = new WeakReference<Class<?>>(cls); } } return cls; }
From source file:org.lenskit.data.dao.file.TextEntitySource.java
/** * Create a file reader.//from w w w . j a v a 2s . c o m * @param name The reader name. * @param object The configuring object. * @param base The base URI for source data. * @return The new entity reader. */ static TextEntitySource fromJSON(String name, JsonNode object, URI base, ClassLoader loader) { TextEntitySource source = new TextEntitySource(name); URI uri = base.resolve(object.get("file").asText()); try { source.setURI(uri.toURL()); } catch (MalformedURLException e) { throw new IllegalArgumentException("Cannot resolve URI " + uri, e); } logger.info("loading text file source {} to read from {}", name, source.getURL()); String fmt = object.path("format").asText("delimited").toLowerCase(); String delim; switch (fmt) { case "csv": delim = ","; break; case "tsv": case "delimited": delim = "\t"; break; default: throw new IllegalArgumentException("unsupported data format " + fmt); } JsonNode delimNode = object.path("delimiter"); if (delimNode.isValueNode()) { delim = delimNode.asText(); } DelimitedColumnEntityFormat format = new DelimitedColumnEntityFormat(); format.setDelimiter(delim); logger.debug("{}: using delimiter {}", name, delim); JsonNode header = object.path("header"); boolean canUseColumnMap = false; if (header.isBoolean() && header.asBoolean()) { logger.debug("{}: reading header", name); format.setHeader(true); canUseColumnMap = true; } else if (header.isNumber()) { format.setHeaderLines(header.asInt()); logger.debug("{}: skipping {} header lines", format.getHeaderLines()); } String eTypeName = object.path("entity_type").asText("rating").toLowerCase(); EntityType etype = EntityType.forName(eTypeName); logger.debug("{}: reading entities of type {}", name, etype); EntityDefaults entityDefaults = EntityDefaults.lookup(etype); format.setEntityType(etype); format.setEntityBuilder( entityDefaults != null ? entityDefaults.getDefaultBuilder() : BasicEntityBuilder.class); JsonNode columns = object.path("columns"); if (columns.isMissingNode() || columns.isNull()) { List<TypedName<?>> defColumns = entityDefaults != null ? entityDefaults.getDefaultColumns() : null; if (defColumns == null) { throw new IllegalArgumentException("no columns specified and no default columns available"); } for (TypedName<?> attr : entityDefaults.getDefaultColumns()) { format.addColumn(attr); } } else if (columns.isObject()) { if (!canUseColumnMap) { throw new IllegalArgumentException("cannot use column map without file header"); } Iterator<Map.Entry<String, JsonNode>> colIter = columns.fields(); while (colIter.hasNext()) { Map.Entry<String, JsonNode> col = colIter.next(); format.addColumn(col.getKey(), parseAttribute(entityDefaults, col.getValue())); } } else if (columns.isArray()) { for (JsonNode col : columns) { format.addColumn(parseAttribute(entityDefaults, col)); } } else { throw new IllegalArgumentException("invalid format for columns"); } JsonNode ebNode = object.path("builder"); if (ebNode.isTextual()) { String ebName = ebNode.asText(); if (ebName.equals("basic")) { format.setEntityBuilder(BasicEntityBuilder.class); } else { Class bld; try { bld = ClassUtils.getClass(loader, ebName); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("cannot load class " + ebName, e); } format.setEntityBuilder(bld); } } logger.debug("{}: using entity builder {}", format.getEntityBuilder()); source.setFormat(format); return source; }
From source file:org.lenskit.data.events.EventTypeResolver.java
/** * Get an event builder for the specified type name. It first looks up the type name using the properties * files loaded from the classpath, then tries to instantiate it as a class. * @param name The type name.//w ww. ja v a 2s .c o m * @return The event builder. */ @Nullable @SuppressWarnings("unchecked") public Class<? extends EventBuilder> getEventBuilder(String name) { String className = typeDefs.getProperty(name); if (className == null) { className = name; } try { return ClassUtils.getClass(classLoader, className).asSubclass(EventBuilder.class); } catch (ClassNotFoundException e) { logger.debug("cannot locate class {}", className); return null; } }