List of usage examples for java.lang Class getClassLoader
@CallerSensitive
@ForceInline
public ClassLoader getClassLoader()
From source file:org.apache.axis.encoding.ser.ArrayDeserializer.java
/** * This method is invoked after startElement when the element requires * deserialization (i.e. the element is not an href & the value is not nil) * DeserializerImpl provides default behavior, which simply * involves obtaining a correct Deserializer and plugging its handler. * @param namespace is the namespace of the element * @param localName is the name of the element * @param prefix is the prefix of the element * @param attributes are the attrs on the element...used to get the type * @param context is the DeserializationContext *//*from ww w . j a v a 2 s .co m*/ public void onStartElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { // Deserializing the xml array requires processing the // xsi:type= attribute, the soapenc:arrayType attribute, // and the xsi:type attributes of the individual elements. // // The xsi:type=<qName> attribute is used to determine the java // type of the array to instantiate. Axis expects it // to be set to the generic "soapenc:Array" or to // a specific qName. If the generic "soapenc:Array" // specification is used, Axis determines the array // type by examining the soapenc:arrayType attribute. // // The soapenc:arrayType=<qname><dims> is used to determine // i) the number of dimensions, // ii) the length of each dimension, // iii) the default xsi:type of each of the elements. // // If the arrayType attribute is missing, Axis assumes // a single dimension array with length equal to the number // of nested elements. In such cases, the default xsi:type of // the elements is determined using the array xsi:type. // // The xsi:type attributes of the individual elements of the // array are used to determine the java type of the element. // If the xsi:type attribute is missing for an element, the // default xsi:type value is used. if (log.isDebugEnabled()) { log.debug("Enter: ArrayDeserializer::startElement()"); } soapConstants = context.getSOAPConstants(); // Get the qname for the array type=, set it to null if // the generic type is used. QName typeQName = context.getTypeFromAttributes(namespace, localName, attributes); if (typeQName == null) { typeQName = getDefaultType(); } if (typeQName != null && Constants.equals(Constants.SOAP_ARRAY, typeQName)) { typeQName = null; } // Now get the arrayType value QName arrayTypeValue = context.getQNameFromString( Constants.getValue(attributes, Constants.URIS_SOAP_ENC, soapConstants.getAttrItemType())); // The first part of the arrayType expression is // the default item type qname. // The second part is the dimension information String dimString = null; QName innerQName = null; String innerDimString = ""; if (arrayTypeValue != null) { if (soapConstants != SOAPConstants.SOAP12_CONSTANTS) { // Doing SOAP 1.1 // Array dimension noted like this : [][x] String arrayTypeValueNamespaceURI = arrayTypeValue.getNamespaceURI(); String arrayTypeValueLocalPart = arrayTypeValue.getLocalPart(); int leftBracketIndex = arrayTypeValueLocalPart.lastIndexOf('['); int rightBracketIndex = arrayTypeValueLocalPart.lastIndexOf(']'); if (leftBracketIndex == -1 || rightBracketIndex == -1 || rightBracketIndex < leftBracketIndex) { throw new IllegalArgumentException(Messages.getMessage("badArrayType00", "" + arrayTypeValue)); } dimString = arrayTypeValueLocalPart.substring(leftBracketIndex + 1, rightBracketIndex); arrayTypeValueLocalPart = arrayTypeValueLocalPart.substring(0, leftBracketIndex); // If multi-dim array set to soapenc:Array if (arrayTypeValueLocalPart.endsWith("]")) { defaultItemType = Constants.SOAP_ARRAY; int bracket = arrayTypeValueLocalPart.indexOf("["); innerQName = new QName(arrayTypeValueNamespaceURI, arrayTypeValueLocalPart.substring(0, bracket)); innerDimString = arrayTypeValueLocalPart.substring(bracket); } else { defaultItemType = new QName(arrayTypeValueNamespaceURI, arrayTypeValueLocalPart); } } else { String arraySizeValue = attributes.getValue(soapConstants.getEncodingURI(), Constants.ATTR_ARRAY_SIZE); int leftStarIndex = arraySizeValue.lastIndexOf('*'); // Skip to num if any if (leftStarIndex != -1) { // "*" => "" if (leftStarIndex == 0 && arraySizeValue.length() == 1) { // "* *" => "" } else if (leftStarIndex == (arraySizeValue.length() - 1)) { throw new IllegalArgumentException( Messages.getMessage("badArraySize00", "" + arraySizeValue)); // "* N" => "N" } else { dimString = arraySizeValue.substring(leftStarIndex + 2); innerQName = arrayTypeValue; innerDimString = arraySizeValue.substring(0, leftStarIndex + 1); } } else { dimString = arraySizeValue; } if (innerDimString == null || innerDimString.length() == 0) { defaultItemType = arrayTypeValue; } else { defaultItemType = Constants.SOAP_ARRAY12; } } } // If no type QName and no defaultItemType qname, use xsd:anyType if (defaultItemType == null && typeQName == null) { Class destClass = context.getDestinationClass(); if (destClass != null && destClass.isArray()) { // This will get set OK down below... } else { defaultItemType = Constants.XSD_ANYTYPE; } } // Determine the class type for the array. arrayClass = null; if (typeQName != null) { arrayClass = context.getTypeMapping().getClassForQName(typeQName); } if (typeQName == null || arrayClass == null) { // type= information is not sufficient. // Get an array of the default item type. Class arrayItemClass = null; QName compQName = defaultItemType; // Nested array, use the innermost qname String dims = "[]"; if (innerQName != null) { compQName = innerQName; if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { // With SOAP 1.2 Array, we append [] for each * found int offset = 0; while ((offset = innerDimString.indexOf('*', offset)) != -1) { dims += "[]"; offset++; } } else { // With SOAP 1.1 Array, we can append directly the complete innerDimString dims += innerDimString; } } // item Class arrayItemClass = context.getTypeMapping().getClassForQName(compQName); if (arrayItemClass != null) { try { // Append the dimension found to the classname computed from the itemClass // to form the array classname // String loadableArrayClassName = JavaUtils .getLoadableClassName(JavaUtils.getTextClassName(arrayItemClass.getName()) + dims); arrayClass = ClassUtils.forName(loadableArrayClassName, true, arrayItemClass.getClassLoader()); } catch (Exception e) { throw new SAXException(Messages.getMessage("noComponent00", "" + defaultItemType)); } } } if (arrayClass == null) { arrayClass = context.getDestinationClass(); } if (arrayClass == null) { throw new SAXException(Messages.getMessage("noComponent00", "" + defaultItemType)); } if (dimString == null || dimString.length() == 0) { // Size determined using length of the members value = new ArrayListExtension(arrayClass); } else { try { StringTokenizer tokenizer; if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { tokenizer = new StringTokenizer(dimString); } else { tokenizer = new StringTokenizer(dimString, "[],"); } length = Integer.parseInt(tokenizer.nextToken()); if (tokenizer.hasMoreTokens()) { // If the array is passed as a multi-dimensional array // (i.e. int[2][3]) then store all of the // mult-dim lengths. // The valueReady method uses this array to set the // proper mult-dim element. mDimLength = new ArrayList(); mDimLength.add(new Integer(length)); while (tokenizer.hasMoreTokens()) { mDimLength.add(new Integer(Integer.parseInt(tokenizer.nextToken()))); } } // Create an ArrayListExtension class to store the ArrayList // plus converted objects. ArrayList list = new ArrayListExtension(arrayClass, length); // This is expensive as our array may not grown this big. // Prevents problems when XML claims a huge size // that it doesn't actually fill. //for (int i = 0; i < length; i++) { // list.add(null); //} value = list; } catch (NumberFormatException e) { throw new IllegalArgumentException(Messages.getMessage("badInteger00", dimString)); } } // If soapenc:offset specified, set the current index accordingly String offset = Constants.getValue(attributes, Constants.URIS_SOAP_ENC, Constants.ATTR_OFFSET); if (offset != null) { if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) { throw new SAXException(Messages.getMessage("noSparseArray")); } int leftBracketIndex = offset.lastIndexOf('['); int rightBracketIndex = offset.lastIndexOf(']'); if (leftBracketIndex == -1 || rightBracketIndex == -1 || rightBracketIndex < leftBracketIndex) { throw new SAXException(Messages.getMessage("badOffset00", offset)); } curIndex = convertToIndex(offset.substring(leftBracketIndex + 1, rightBracketIndex), "badOffset00"); } if (log.isDebugEnabled()) { log.debug("Exit: ArrayDeserializer::startElement()"); } }
From source file:org.evosuite.setup.TestUsageChecker.java
public static boolean canUse(Method m, Class<?> ownerClass) { if (m.isBridge()) { logger.debug("Excluding bridge method: " + m.toString()); return false; }/* www . j a v a 2 s. c om*/ if (m.isSynthetic()) { logger.debug("Excluding synthetic method: " + m.toString()); return false; } if (!Properties.USE_DEPRECATED && m.isAnnotationPresent(Deprecated.class)) { final Class<?> targetClass = Properties.getTargetClassAndDontInitialise(); if (Properties.hasTargetClassBeenLoaded() && !m.getDeclaringClass().equals(targetClass)) { logger.debug("Excluding deprecated method " + m.getName()); return false; } } if (m.isAnnotationPresent(Test.class) || m.isAnnotationPresent(Before.class) || m.isAnnotationPresent(BeforeClass.class) || m.isAnnotationPresent(After.class) || m.isAnnotationPresent(AfterClass.class)) { logger.debug("Excluding test method " + m.getName()); return false; } if (m.isAnnotationPresent(EvoSuiteTest.class)) { logger.debug("Excluding EvoSuite test method " + m.getName()); return false; } if (m.isAnnotationPresent(EvoSuiteExclude.class)) { logger.debug("Excluding method with exclusion annotation " + m.getName()); return false; } if (m.getDeclaringClass().equals(java.lang.Object.class)) { return false; } if (!m.getReturnType().equals(String.class) && (!canUse(m.getReturnType()) || !canUse(m.getGenericReturnType()))) { return false; } for (java.lang.reflect.Type paramType : m.getGenericParameterTypes()) { if (!canUse(paramType)) return false; } if (m.getDeclaringClass().equals(Enum.class)) { return false; /* if (m.getName().equals("valueOf") || m.getName().equals("values") || m.getName().equals("ordinal")) { logger.debug("Excluding valueOf for Enum " + m.toString()); return false; } // Skip compareTo on enums (like Randoop) if (m.getName().equals("compareTo") && m.getParameterTypes().length == 1 && m.getParameterTypes()[0].equals(Enum.class)) return false; */ } if (m.getDeclaringClass().equals(java.lang.Thread.class)) return false; // Hashcode only if we need to cover it if (m.getName().equals("hashCode")) { final Class<?> targetClass = Properties.getTargetClassAndDontInitialise(); if (!m.getDeclaringClass().equals(targetClass)) return false; else { if (GraphPool.getInstance(ownerClass.getClassLoader()).getActualCFG(Properties.TARGET_CLASS, m.getName() + Type.getMethodDescriptor(m)) == null) { // Don't cover generated hashCode // TODO: This should work via annotations return false; } } } // Randoop special case: just clumps together a bunch of hashCodes, so skip it if (m.getName().equals("deepHashCode") && m.getDeclaringClass().equals(Arrays.class)) return false; // Randoop special case: differs too much between JDK installations if (m.getName().equals("getAvailableLocales")) return false; if (m.getName().equals(ClassResetter.STATIC_RESET)) { logger.debug("Ignoring static reset method"); return false; } if (isForbiddenNonDeterministicCall(m)) { return false; } if (!Properties.CONSIDER_MAIN_METHODS && m.getName().equals("main") && Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers())) { logger.debug("Ignoring static main method "); return false; } /* if(m.getTypeParameters().length > 0) { logger.debug("Cannot handle generic methods at this point"); if(m.getDeclaringClass().equals(Properties.getTargetClass())) { LoggingUtils.getEvoLogger().info("* Skipping method "+m.getName()+": generic methods are not handled yet"); } return false; } */ // If default or if (Modifier.isPublic(m.getModifiers())) { TestClusterUtils.makeAccessible(m); return true; } // If default access rights, then check if this class is in the same package as the target class if (!Modifier.isPrivate(m.getModifiers())) { // && !Modifier.isProtected(m.getModifiers())) { String packageName = ClassUtils.getPackageName(ownerClass); String declaredPackageName = ClassUtils.getPackageName(m.getDeclaringClass()); if (packageName.equals(Properties.CLASS_PREFIX) && packageName.equals(declaredPackageName)) { TestClusterUtils.makeAccessible(m); return true; } } return false; }
From source file:org.gradle.model.internal.manage.schema.extract.ManagedProxyClassGenerator.java
/** * Generates an implementation of the given managed type. * <p>/*from w ww .j a v a 2 s . c o m*/ * The generated class will implement/extend the managed type and will: * <ul> * <li>provide implementations for abstract getters and setters that delegate to model nodes</li> * <li>provide a `toString()` implementation</li> * <li>mix-in implementation of {@link ManagedInstance}</li> * <li>provide a constructor that accepts a {@link ModelElementState}, which will be used to implement the above.</li> * </ul> * * In case a delegate schema is supplied, the generated class will also have: * <ul> * <li>a constructor that also takes a delegate instance</li> * <li>methods that call through to the delegate instance</li> * </ul> */ public <T, M extends T, D extends T> Class<? extends M> generate(ModelStructSchema<M> managedSchema, ModelStructSchema<D> delegateSchema) { if (delegateSchema != null && Modifier.isAbstract(delegateSchema.getType().getConcreteClass().getModifiers())) { throw new IllegalArgumentException("Delegate type must be null or a non-abstract type"); } ClassWriter visitor = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); ModelType<M> managedType = managedSchema.getType(); StringBuilder generatedTypeNameBuilder = new StringBuilder(managedType.getName()); if (delegateSchema != null) { generatedTypeNameBuilder.append("$BackedBy_") .append(delegateSchema.getType().getName().replaceAll("\\.", "_")); } else { generatedTypeNameBuilder.append("$Impl"); } String generatedTypeName = generatedTypeNameBuilder.toString(); Type generatedType = Type.getType("L" + generatedTypeName.replaceAll("\\.", "/") + ";"); Class<M> managedTypeClass = managedType.getConcreteClass(); Class<?> superclass; final ImmutableSet.Builder<String> interfaceInternalNames = ImmutableSet.builder(); final ImmutableSet.Builder<Class<?>> typesToDelegate = ImmutableSet.builder(); typesToDelegate.add(managedTypeClass); interfaceInternalNames.add(MANAGED_INSTANCE_TYPE); if (managedTypeClass.isInterface()) { superclass = Object.class; interfaceInternalNames.add(Type.getInternalName(managedTypeClass)); } else { superclass = managedTypeClass; } // TODO:LPTR This should be removed once BinaryContainer is a ModelMap // We need to also implement all the interfaces of the delegate type because otherwise // BinaryContainer won't recognize managed binaries as BinarySpecInternal if (delegateSchema != null) { ModelSchemaUtils.walkTypeHierarchy(delegateSchema.getType().getConcreteClass(), new ModelSchemaUtils.TypeVisitor<D>() { @Override public void visitType(Class<? super D> type) { if (type.isInterface()) { typesToDelegate.add(type); interfaceInternalNames.add(Type.getInternalName(type)); } } }); } generateProxyClass(visitor, managedSchema, delegateSchema, interfaceInternalNames.build(), typesToDelegate.build(), generatedType, Type.getType(superclass)); return defineClass(visitor, managedTypeClass.getClassLoader(), generatedTypeName); }
From source file:org.apache.hadoop.hive.ql.exec.Utilities.java
/** * Returns the full path to the Jar containing the class. It always return a JAR. * * @param klass//from www. jav a 2 s . c o m * class. * * @return path to the Jar containing the class. */ @SuppressWarnings("rawtypes") public static String jarFinderGetJar(Class klass) { Preconditions.checkNotNull(klass, "klass"); ClassLoader loader = klass.getClassLoader(); if (loader != null) { String class_file = klass.getName().replaceAll("\\.", "/") + ".class"; try { for (Enumeration itr = loader.getResources(class_file); itr.hasMoreElements();) { URL url = (URL) itr.nextElement(); String path = url.getPath(); if (path.startsWith("file:")) { path = path.substring("file:".length()); } path = URLDecoder.decode(path, "UTF-8"); if ("jar".equals(url.getProtocol())) { path = URLDecoder.decode(path, "UTF-8"); return path.replaceAll("!.*$", ""); } } } catch (IOException e) { throw new RuntimeException(e); } } return null; }
From source file:com.emc.storageos.coordinator.client.service.impl.CoordinatorClientImpl.java
@Override public <T> T locateService(Class<T> clazz, String name, String version, String tag, String endpointKey) throws CoordinatorException { String key = String.format("%1$s:%2$s:%3$s:%4$s", name, version, tag, endpointKey); Object proxy = _proxyCache.get(key); if (proxy == null) { List<Service> services = locateAllServices(name, version, tag, endpointKey); if (services == null || services.isEmpty()) { throw CoordinatorException.retryables.unableToLocateService(name, version, tag, endpointKey); }//from ww w . ja va2 s. c o m Service service = services.get(0); URI endpoint = service.getEndpoint(endpointKey); if (endpoint == null) { throw CoordinatorException.retryables.unableToLocateServiceNoEndpoint(name, version, tag, endpointKey); } // check local host IPv6/IPv4 endpoint = getInetAddessLookupMap().expandURI(endpoint); if (endpoint.getScheme().equals("rmi")) { RmiInvocationHandler handler = new RmiInvocationHandler(); handler.setName(name); handler.setVersion(version); handler.setTag(tag); handler.setEndpointKey(endpointKey); handler.setEndpointInterface(clazz); handler.setCoordinator(this); proxy = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, handler); _proxyCache.putIfAbsent(key, proxy); } else { throw CoordinatorException.retryables.unsupportedEndPointSchema(endpoint.getScheme()); } } return clazz.cast(proxy); }
From source file:org.sakaiproject.genericdao.springjdbc.JdbcGenericDao.java
/** * Initialize the persistent classes/*from w w w .j a va2 s .c o m*/ */ protected void initPersistentClasses() { // init the list of classes and mappers related to them and execute DDL if needed for (Class<?> type : getPersistentClasses()) { DataMapper dm = getDataMapper(type); if (autoDDL) { InputStream ddlIS = null; // try to get DDL from the mapper first String ddl = dm.generateDDL(getDatabaseType()); if (ddl == null || "".equals(ddl)) { if (dm instanceof SimpleDataMapper) { // try loading from a file if set SimpleDataMapper sdm = (SimpleDataMapper) dm; String filepath = sdm.getDbTypeToFilename().get(getDatabaseType()); if (filepath != null) { // cleanup filename if (filepath.startsWith("/")) { filepath = filepath.substring(1); } // try looking in the classloader of the thread first ddlIS = getInputStreamFromClassloader(Thread.currentThread().getContextClassLoader(), filepath); if (ddlIS == null) { // next try the classloader for this DAO ddlIS = getInputStreamFromClassloader(this.getClass().getClassLoader(), filepath); } if (ddlIS == null) { // next try the classloader for persistent type ddlIS = getInputStreamFromClassloader(type.getClassLoader(), filepath); } if (ddlIS == null) { // we got a filename but did not find the file contents, we need to die throw new IllegalArgumentException("Could not find find DDL file resource (" + filepath + ") for DB (" + getDatabaseType() + ") in any searched classloader, cannot execute DDL"); } } } else { // nothing to do here: we have a blank ddl and this is not a simple mapper so just continue on -AZ } } else { // turn DDL into an IS ddlIS = new ByteArrayInputStream(ddl.getBytes()); } if (ddlIS != null) { // execute the ddl executeDDLforType(ddlIS, type); } } } }
From source file:org.apache.solr.core.SolrResourceLoader.java
/** * This method loads a class either with its FQN or a short-name (solr.class-simplename or class-simplename). * It tries to load the class with the name that is given first and if it fails, it tries all the known * solr packages. This method caches the FQN of a short-name in a static map in-order to make subsequent lookups * for the same class faster. The caching is done only if the class is loaded by the webapp classloader and it * is loaded using a shortname./*from w ww . j a v a 2 s. co m*/ * * @param cname The name or the short name of the class. * @param subpackages the packages to be tried if the cname starts with solr. * @return the loaded class. An exception is thrown if it fails */ public <T> Class<? extends T> findClass(String cname, Class<T> expectedType, String... subpackages) { if (subpackages == null || subpackages.length == 0 || subpackages == packages) { subpackages = packages; String c = classNameCache.get(cname); if (c != null) { try { return Class.forName(c, true, classLoader).asSubclass(expectedType); } catch (ClassNotFoundException e) { //this is unlikely log.error("Unable to load cached class-name : " + c + " for shortname : " + cname + e); } } } Class<? extends T> clazz = null; try { // first try legacy analysis patterns, now replaced by Lucene's Analysis package: final Matcher m = legacyAnalysisPattern.matcher(cname); if (m.matches()) { final String name = m.group(4); log.trace("Trying to load class from analysis SPI using name='{}'", name); try { if (CharFilterFactory.class.isAssignableFrom(expectedType)) { return clazz = CharFilterFactory.lookupClass(name).asSubclass(expectedType); } else if (TokenizerFactory.class.isAssignableFrom(expectedType)) { return clazz = TokenizerFactory.lookupClass(name).asSubclass(expectedType); } else if (TokenFilterFactory.class.isAssignableFrom(expectedType)) { return clazz = TokenFilterFactory.lookupClass(name).asSubclass(expectedType); } else { log.warn( "'{}' looks like an analysis factory, but caller requested different class type: {}", cname, expectedType.getName()); } } catch (IllegalArgumentException ex) { // ok, we fall back to legacy loading } } // first try cname == full name try { return clazz = Class.forName(cname, true, classLoader).asSubclass(expectedType); } catch (ClassNotFoundException e) { String newName = cname; if (newName.startsWith(project)) { newName = cname.substring(project.length() + 1); } for (String subpackage : subpackages) { try { String name = base + '.' + subpackage + newName; log.trace("Trying class name " + name); return clazz = Class.forName(name, true, classLoader).asSubclass(expectedType); } catch (ClassNotFoundException e1) { // ignore... assume first exception is best. } } throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error loading class '" + cname + "'", e); } } finally { if (clazz != null) { //cache the shortname vs FQN if it is loaded by the webapp classloader and it is loaded // using a shortname if (clazz.getClassLoader() == SolrResourceLoader.class.getClassLoader() && !cname.equals(clazz.getName()) && (subpackages.length == 0 || subpackages == packages)) { //store in the cache classNameCache.put(cname, clazz.getName()); } // print warning if class is deprecated if (clazz.isAnnotationPresent(Deprecated.class)) { log.warn( "Solr loaded a deprecated plugin/analysis class [{}]. Please consult documentation how to replace it accordingly.", cname); } } } }
From source file:com.openddal.test.BaseTestCase.java
/** * Verify the next method call on the object will throw an exception. * * @param <T> the class of the object * @param verifier the result verifier to call * @param obj the object to wrap/*from w ww .j av a 2 s . co m*/ * @return a proxy for the object */ @SuppressWarnings("unchecked") protected <T> T assertThrows(final ResultVerifier verifier, final T obj) { Class<?> c = obj.getClass(); InvocationHandler ih = new InvocationHandler() { private Exception called = new Exception("No method called"); @Override protected void finalize() { if (called != null) { called.printStackTrace(System.err); } } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Exception { try { called = null; Object ret = method.invoke(obj, args); verifier.verify(ret, null, method, args); return ret; } catch (InvocationTargetException e) { verifier.verify(null, e.getTargetException(), method, args); Class<?> retClass = method.getReturnType(); if (!retClass.isPrimitive()) { return null; } if (retClass == boolean.class) { return false; } else if (retClass == byte.class) { return (byte) 0; } else if (retClass == char.class) { return (char) 0; } else if (retClass == short.class) { return (short) 0; } else if (retClass == int.class) { return 0; } else if (retClass == long.class) { return 0L; } else if (retClass == float.class) { return 0F; } else if (retClass == double.class) { return 0D; } return null; } } }; if (!ProxyCodeGenerator.isGenerated(c)) { Class<?>[] interfaces = c.getInterfaces(); if (Modifier.isFinal(c.getModifiers()) || (interfaces.length > 0 && getClass() != c)) { // interface class proxies if (interfaces.length == 0) { throw new RuntimeException("Can not create a proxy for the class " + c.getSimpleName() + " because it doesn't implement any interfaces and is final"); } return (T) Proxy.newProxyInstance(c.getClassLoader(), interfaces, ih); } } try { Class<?> pc = ProxyCodeGenerator.getClassProxy(c); Constructor<?> cons = pc.getConstructor(InvocationHandler.class); return (T) cons.newInstance(ih); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.catalina.loader.WebappClassLoader.java
/** * Find the specified class in our local repositories, if possible. If * not found, throw <code>ClassNotFoundException</code>. * * @param name Name of the class to be loaded * * @exception ClassNotFoundException if the class was not found */// ww w . j a v a 2 s . c o m public Class findClass(String name) throws ClassNotFoundException { if (log.isDebugEnabled()) log.debug(" findClass(" + name + ")"); // (1) Permission to define this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { if (log.isTraceEnabled()) log.trace(" securityManager.checkPackageDefinition"); securityManager.checkPackageDefinition(name.substring(0, i)); } catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); } } } // Ask our superclass to locate this class, if possible // (throws ClassNotFoundException if it is not found) Class clazz = null; try { if (log.isTraceEnabled()) log.trace(" findClassInternal(" + name + ")"); try { clazz = findClassInternal(name); } catch (ClassNotFoundException cnfe) { if (!hasExternalRepositories) { throw cnfe; } } catch (AccessControlException ace) { throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } if ((clazz == null) && hasExternalRepositories) { try { clazz = super.findClass(name); } catch (AccessControlException ace) { throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if (clazz == null) { if (log.isDebugEnabled()) log.debug(" --> Returning ClassNotFoundException"); throw new ClassNotFoundException(name); } } catch (ClassNotFoundException e) { if (log.isTraceEnabled()) log.trace(" --> Passing on ClassNotFoundException"); throw e; } // Return the class we have located if (log.isTraceEnabled()) log.debug(" Returning class " + clazz); if ((log.isTraceEnabled()) && (clazz != null)) log.debug(" Loaded by " + clazz.getClassLoader()); return (clazz); }
From source file:org.eobjects.analyzer.util.convert.StandardTypeConverter.java
@Override public Object fromString(Class<?> type, String str) { if (ReflectionUtils.isString(type)) { return str; }//from w ww. j a v a2s.c o m if (ReflectionUtils.isBoolean(type)) { return Boolean.valueOf(str); } if (ReflectionUtils.isCharacter(type)) { return Character.valueOf(str.charAt(0)); } if (ReflectionUtils.isInteger(type)) { return Integer.valueOf(str); } if (ReflectionUtils.isLong(type)) { return Long.valueOf(str); } if (ReflectionUtils.isByte(type)) { return Byte.valueOf(str); } if (ReflectionUtils.isShort(type)) { return Short.valueOf(str); } if (ReflectionUtils.isDouble(type)) { return Double.valueOf(str); } if (ReflectionUtils.isFloat(type)) { return Float.valueOf(str); } if (ReflectionUtils.is(type, Class.class)) { try { return Class.forName(str); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Class not found: " + str, e); } } if (type.isEnum()) { try { Object[] enumConstants = type.getEnumConstants(); // first look for enum constant matches Method nameMethod = Enum.class.getMethod("name"); for (Object e : enumConstants) { String name = (String) nameMethod.invoke(e); if (name.equals(str)) { return e; } } // check for aliased enums for (Object e : enumConstants) { String name = (String) nameMethod.invoke(e); Field field = type.getField(name); Alias alias = ReflectionUtils.getAnnotation(field, Alias.class); if (alias != null) { String[] aliasValues = alias.value(); for (String aliasValue : aliasValues) { if (aliasValue.equals(str)) { return e; } } } } } catch (Exception e) { throw new IllegalStateException("Unexpected error occurred while examining enum", e); } throw new IllegalArgumentException("No such enum '" + str + "' in enum class: " + type.getName()); } if (ReflectionUtils.isDate(type)) { return toDate(str); } if (ReflectionUtils.is(type, File.class)) { return new File(str.replace('\\', File.separatorChar)); } if (ReflectionUtils.is(type, Calendar.class)) { Date date = toDate(str); Calendar c = Calendar.getInstance(); c.setTime(date); return c; } if (ReflectionUtils.is(type, Pattern.class)) { try { return Pattern.compile(str); } catch (PatternSyntaxException e) { throw new IllegalArgumentException("Invalid regular expression syntax in '" + str + "'.", e); } } if (ReflectionUtils.is(type, java.sql.Date.class)) { Date date = toDate(str); return new java.sql.Date(date.getTime()); } if (ReflectionUtils.isNumber(type)) { return ConvertToNumberTransformer.transformValue(str); } if (ReflectionUtils.is(type, Serializable.class)) { logger.warn("fromString(...): No built-in handling of type: {}, using deserialization", type.getName()); byte[] bytes = (byte[]) parentConverter.fromString(byte[].class, str); ChangeAwareObjectInputStream objectInputStream = null; try { objectInputStream = new ChangeAwareObjectInputStream(new ByteArrayInputStream(bytes)); objectInputStream.addClassLoader(type.getClassLoader()); Object obj = objectInputStream.readObject(); return obj; } catch (Exception e) { throw new IllegalStateException("Could not deserialize to " + type + ".", e); } finally { FileHelper.safeClose(objectInputStream); } } throw new IllegalArgumentException("Could not convert to type: " + type.getName()); }