List of usage examples for java.lang Class getClassLoader
@CallerSensitive
@ForceInline
public ClassLoader getClassLoader()
From source file:org.apache.hadoop.hbase.ipc.ProtobufRpcClientEngine.java
@Override public IpcProtocol getProxy(Class<? extends IpcProtocol> protocol, InetSocketAddress addr, User ticket, Configuration conf, SocketFactory factory, int rpcTimeout) throws IOException { final Invoker invoker = new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout); return (IpcProtocol) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, invoker); }
From source file:com.netflix.paas.config.base.JavaAssistArchaeusConfigurationFactory.java
@SuppressWarnings({ "unchecked", "static-access" }) public <T> T get(Class<T> configClass, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) throws Exception { final Map<String, Supplier<?>> methods = ConfigurationProxyUtils.getMethodSuppliers(configClass, propertyFactory, configuration); if (configClass.isInterface()) { Class<?> proxyClass = Proxy.getProxyClass(configClass.getClassLoader(), new Class[] { configClass }); return (T) proxyClass.getConstructor(new Class[] { InvocationHandler.class }) .newInstance(new Object[] { new InvocationHandler() { @Override//w ww .j av a 2s . c o m public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Supplier<?> supplier = (Supplier<?>) methods.get(method.getName()); if (supplier == null) { return method.invoke(proxy, args); } return supplier.get(); } } }); } else { final Enhancer enhancer = new Enhancer(); final Object obj = (T) enhancer.create(configClass, new net.sf.cglib.proxy.InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Supplier<?> supplier = (Supplier<?>) methods.get(method.getName()); if (supplier == null) { return method.invoke(proxy, args); } return supplier.get(); } }); ConfigurationProxyUtils.assignFieldValues(obj, configClass, propertyFactory, configuration); return (T) obj; } }
From source file:net.darkmist.alib.res.PkgRes.java
public PkgRes(Class<?> cls) { if (cls == null) throw new NullPointerException("cls is null"); this.loader = cls.getClassLoader(); prefix = appendResourcePathPrefixFor(null, cls).toString(); }
From source file:ca.uhn.fhir.rest.client.RestfulClientFactory.java
@SuppressWarnings("unchecked") private <T extends IRestfulClient> T instantiateProxy(Class<T> theClientType, InvocationHandler theInvocationHandler) { T proxy = (T) Proxy.newProxyInstance(theClientType.getClassLoader(), new Class[] { theClientType }, theInvocationHandler);//from w ww . ja va2 s . c o m return proxy; }
From source file:org.freezedry.serialization.ObjectSerializer.java
@Override public synchronized <T> T deserialize(final InputStream input, final Class<T> clazz) { // read the input stream into an object. we use the the (apache commons-io) ClassLoaderObjectInputStream // to read the object because we need to be able to use the same class loader that loaded the class in // the first place (for example, the RestfulClassLoader). T object;// w ww . j a v a 2s . co m try (final ClassLoaderObjectInputStream in = new ClassLoaderObjectInputStream(clazz.getClassLoader(), input)) { object = clazz.cast(in.readObject()); } catch (IOException | ClassNotFoundException e) { final StringBuilder message = new StringBuilder(); message.append("Unable to serialize object to output stream:").append(Constants.NEW_LINE); message.append(" Input Stream Type: ").append(input.getClass().getName()).append(Constants.NEW_LINE); message.append(" Object Type: ").append(clazz.getName()).append(Constants.NEW_LINE); LOGGER.error(message.toString(), e); throw new IllegalArgumentException(message.toString(), e); } return object; }
From source file:org.apache.fop.events.DefaultEventBroadcaster.java
/** * Creates a dynamic proxy for the given EventProducer interface that will handle the * conversion of the method call into the broadcasting of an event instance. * @param clazz a descendant interface of EventProducer * @return the EventProducer instance/*from w w w. j a v a 2 s .c om*/ */ protected EventProducer createProxyFor(Class clazz) { final EventProducerModel producerModel = getEventProducerModel(clazz); if (producerModel == null) { throw new IllegalStateException("Event model doesn't contain the definition for " + clazz.getName()); } return (EventProducer) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); EventMethodModel methodModel = producerModel.getMethod(methodName); String eventID = producerModel.getInterfaceName() + "." + methodName; if (methodModel == null) { throw new IllegalStateException("Event model isn't consistent" + " with the EventProducer interface. Please rebuild FOP!" + " Affected method: " + eventID); } Map params = new java.util.HashMap(); int i = 1; Iterator iter = methodModel.getParameters().iterator(); while (iter.hasNext()) { EventMethodModel.Parameter param = (EventMethodModel.Parameter) iter.next(); params.put(param.getName(), args[i]); i++; } Event ev = new Event(args[0], eventID, methodModel.getSeverity(), params); broadcastEvent(ev); if (ev.getSeverity() == EventSeverity.FATAL) { EventExceptionManager.throwException(ev, methodModel.getExceptionClass()); } return null; } }); }
From source file:fast.servicescreen.server.RequestServiceImpl.java
private String getClassLocation() { Class<? extends RequestServiceImpl> myClass = this.getClass(); String myClassName = myClass.getName(); String resourceName = myClassName.replace('.', '/') + ".class"; String classpath = myClass.getClassLoader().getResource(resourceName).toString(); // cut file: prefix classpath = classpath.substring("file:".length()); return classpath; }
From source file:appeng.recipes.loader.RecipeResourceCopier.java
/** * List directory contents for a resource folder. Not recursive. This is basically a brute-force implementation. Works for regular files and also JARs. * * @param clazz Any java class that lives in the same place as the resources you want. * @param path Should end with "/", but not start with one. * * @return Just the name of each member item, not the full paths. * * @throws URISyntaxException if it is a file path and the URL can not be converted to URI * @throws IOException if jar path can not be decoded * @throws UnsupportedOperationException if it is neither in jar nor in file path *///from w w w . j av a2 s . c om @Nonnull private String[] getResourceListing(@Nonnull final Class<?> clazz, @Nonnull final String path) throws URISyntaxException, IOException { assert clazz != null; assert path != null; final ClassLoader classLoader = clazz.getClassLoader(); if (classLoader == null) { throw new IllegalStateException( "ClassLoader was not found. It was probably loaded at a inappropriate time"); } URL dirURL = classLoader.getResource(path); if (dirURL != null) { final String protocol = dirURL.getProtocol(); if (protocol.equals(FILE_PROTOCOL)) { // A file path: easy enough final URI uriOfURL = dirURL.toURI(); final File fileOfURI = new File(uriOfURL); final String[] filesAndDirectoriesOfURI = fileOfURI.list(); if (filesAndDirectoriesOfURI == null) { throw new IllegalStateException( "Files and Directories were illegal. Either an abstract pathname does not denote a directory, or an I/O error occured."); } else { return filesAndDirectoriesOfURI; } } } if (dirURL == null) { /* * In case of a jar file, we can't actually find a directory. * Have to assume the same jar as clazz. */ final String className = clazz.getName(); final Matcher matcher = DOT_COMPILE_PATTERN.matcher(className); final String me = matcher.replaceAll("/") + CLASS_EXTENSION; dirURL = classLoader.getResource(me); } if (dirURL != null) { final String protocol = dirURL.getProtocol(); if (protocol.equals(JAR_PROTOCOL)) { /* A JAR path */ final String dirPath = dirURL.getPath(); final String jarPath = dirPath.substring(5, dirPath.indexOf('!')); // strip out only // the JAR file final JarFile jar = new JarFile(URLDecoder.decode(jarPath, UTF_8_ENCODING)); try { final Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries in jar final Collection<String> result = new HashSet<String>(INITIAL_RESOURCE_CAPACITY); // avoid duplicates // in case it is a // subdirectory while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); final String entryFullName = entry.getName(); if (entryFullName.startsWith(path)) { // filter according to the path String entryName = entryFullName.substring(path.length()); final int checkSubDir = entryName.indexOf('/'); if (checkSubDir >= 0) { // if it is a subdirectory, we just return the directory name entryName = entryName.substring(0, checkSubDir); } result.add(entryName); } } return result.toArray(new String[result.size()]); } finally { jar.close(); } } } throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); }
From source file:net.darkmist.alib.res.PkgRes.java
public PkgRes(Object obj) { Class<?> cls; if (obj == null) throw new NullPointerException("obj is null"); cls = obj.getClass();/* w w w.j a va2 s. c om*/ loader = cls.getClassLoader(); prefix = appendResourcePathPrefixFor(null, cls).toString(); }
From source file:com.seer.datacruncher.eventtrigger.DynamicClassLoader.java
public Object newProxyInstance(Class interfaceClass, String implClassName) throws RuntimeException { JVInvocationHandler handler = new JVInvocationHandler(implClassName); return Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] { interfaceClass }, handler); }