Example usage for java.lang Class getName

List of usage examples for java.lang Class getName

Introduction

In this page you can find the example usage for java.lang Class getName.

Prototype

public String getName() 

Source Link

Document

Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String .

Usage

From source file:com.asakusafw.compiler.bootstrap.OperatorCompilerDriver.java

private static File findSource(File sourcePath, Class<?> aClass) throws IOException {
    assert sourcePath != null;
    assert aClass != null;
    String[] segments = aClass.getName().split("\\."); //$NON-NLS-1$
    File current = sourcePath;/*w  w w.j a  va  2s .  c  om*/
    for (int i = 0; i < segments.length - 1; i++) {
        current = new File(current, segments[i]);
        if (current.isDirectory() == false) {
            throw new FileNotFoundException(MessageFormat.format("{0} (for {1})", current, aClass.getName()));
        }
    }
    String name = segments[segments.length - 1];
    int enclosing = name.indexOf('$');
    if (enclosing >= 0) {
        name = name.substring(0, enclosing);
    }
    File file = new File(current, name + ".java"); //$NON-NLS-1$
    if (file.isFile() == false) {
        if (current.isDirectory() == false) {
            throw new FileNotFoundException(MessageFormat.format("{0} (for {1})", file, aClass.getName()));
        }
    }
    return file.getCanonicalFile();
}

From source file:Which4J.java

/**
 * Search the specified classloader for the given class object.
 * /*from w ww . j  a  v a2  s .c  om*/
 * @param clazz the class object to search for
 * @param loader the classloader to search
 * @return the source location of the resource, or null if it wasn't found
 */
public static String which(Class clazz, ClassLoader loader) {
    return which(clazz.getName(), loader);
}

From source file:com.addthis.codec.jackson.MissingPropertyException.java

public static MissingPropertyException from(JsonParser jp, Object fromObjectOrClass, String propertyName,
        Collection<Object> propertyIds) {
    if (fromObjectOrClass == null) {
        throw new IllegalArgumentException();
    }//from   w  w  w  .  ja  v a  2s. c om
    Class<?> ref;
    if (fromObjectOrClass instanceof Class<?>) {
        ref = (Class<?>) fromObjectOrClass;
    } else {
        ref = fromObjectOrClass.getClass();
    }
    String msg = "Missing field \"" + propertyName + "\" (class " + ref.getName() + "), marked as required";
    MissingPropertyException e = new MissingPropertyException(msg, jp.getCurrentLocation(), ref, propertyName,
            propertyIds);
    // but let's also ensure path includes this last (missing) segment
    e.prependPath(fromObjectOrClass, propertyName);
    return e;
}

From source file:com.asakusafw.testdriver.tools.runner.BatchTestTruncator.java

private static void resolveBatch(Conf conf, Class<? extends BatchDescription> aClass) {
    LOG.debug("analyzing batch: {}", aClass.getName()); //$NON-NLS-1$
    List<Class<? extends FlowDescription>> flows = new ArrayList<>();
    try {/*from   w  w  w . j a  v  a2 s . c o m*/
        BatchDescription batch = aClass.newInstance();
        batch.start();
        for (Work work : batch.getWorks()) {
            WorkDescription desc = work.getDescription();
            if (desc instanceof JobFlowWorkDescription) {
                Class<? extends FlowDescription> flow = ((JobFlowWorkDescription) desc).getFlowClass();
                flows.add(flow);
            }
        }
    } catch (ReflectiveOperationException e) {
        throw new IllegalArgumentException(
                MessageFormat.format(Messages.getString("BatchTestTruncator.errorInvalidBatchClass"), //$NON-NLS-1$
                        aClass.getName()));
    }
    for (Class<? extends FlowDescription> flow : flows) {
        resolveFlow(conf, flow);
    }
}

From source file:com.singular.utils.FileUtils.java

/**
 * Taken from apache hadoop project.//w w  w.j  a  v  a  2s . c o m
 * Apache 2.0 license.
 *
 * @param className
 * @return
 */
public static String findContainingJar(Class className) {
    ClassLoader loader = className.getClassLoader();
    String classFile = className.getName().replaceAll("\\.", "/") + ".class";

    try {
        for (Enumeration itr = loader.getResources(classFile); itr.hasMoreElements();) {
            URL url = (URL) itr.nextElement();

            if ("jar".equals(url.getProtocol())) {
                String toReturn = url.getPath();
                if (toReturn.startsWith("file:")) {
                    toReturn = toReturn.substring("file:".length());
                }
                toReturn = toReturn.replaceAll("\\+", "%2B");
                toReturn = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:de.xwic.appkit.core.transport.xml.EtoEntityNodeParser.java

/**
 * @param entityClass/*from www. ja  v a2  s. c  o m*/
 * @param etoClass
 * @return
 */
private static boolean requiresNewDescriptor(final Class<?> entityClass, final Class<?> etoClass) {
    if (etoClass == null) {
        return false;
    }
    return !etoClass.getName().equals(entityClass.getName());
}

From source file:ca.psiphon.tunneledwebview.WebViewProxySettings.java

@TargetApi(Build.VERSION_CODES.KITKAT) // for android.util.ArrayMap methods
@SuppressWarnings("rawtypes")
private static boolean setWebkitProxyLollipop(Context appContext, String host, int port) {
    System.setProperty("http.proxyHost", host);
    System.setProperty("http.proxyPort", port + "");
    System.setProperty("https.proxyHost", host);
    System.setProperty("https.proxyPort", port + "");
    try {/*  w w w.j  a va  2 s .  c  o m*/
        Class applictionClass = Class.forName("android.app.Application");
        Field mLoadedApkField = applictionClass.getDeclaredField("mLoadedApk");
        mLoadedApkField.setAccessible(true);
        Object mloadedApk = mLoadedApkField.get(appContext);
        Class loadedApkClass = Class.forName("android.app.LoadedApk");
        Field mReceiversField = loadedApkClass.getDeclaredField("mReceivers");
        mReceiversField.setAccessible(true);
        ArrayMap receivers = (ArrayMap) mReceiversField.get(mloadedApk);
        for (Object receiverMap : receivers.values()) {
            for (Object receiver : ((ArrayMap) receiverMap).keySet()) {
                Class clazz = receiver.getClass();
                if (clazz.getName().contains("ProxyChangeListener")) {
                    Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class);
                    Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
                    onReceiveMethod.invoke(receiver, appContext, intent);
                }
            }
        }
        return true;
    } catch (ClassNotFoundException e) {
    } catch (NoSuchFieldException e) {
    } catch (IllegalAccessException e) {
    } catch (NoSuchMethodException e) {
    } catch (InvocationTargetException e) {
    }
    return false;
}

From source file:cop.raml.mocks.MockUtils.java

private static TypeElementMock createPrimitiveElement(@NotNull Class<?> cls) {
    TypeElementMock element = new TypeElementMock(cls.getName(), ElementKind.CLASS);
    element.setType(new TypeMirrorMock(element, TypeMirrorMock.getTypeKind(cls)));
    return setAnnotations(element, cls);
}

From source file:Main.java

/**
 * <p>Adds all the elements of the given arrays into a new array.</p>
 * <p>The new array contains all of the element of {@code array1} followed
 * by all of the elements {@code array2}. When an array is returned, it is always
 * a new array.</p>// w w  w .ja  v  a  2s.  com
 *
 * <pre>
 * ArrayUtils.addAll(null, null)     = null
 * ArrayUtils.addAll(array1, null)   = cloned copy of array1
 * ArrayUtils.addAll(null, array2)   = cloned copy of array2
 * ArrayUtils.addAll([], [])         = []
 * ArrayUtils.addAll([null], [null]) = [null, null]
 * ArrayUtils.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]
 * </pre>
 *
 * @param <T> the component type of the array
 * @param array1  the first array whose elements are added to the new array, may be {@code null}
 * @param array2  the second array whose elements are added to the new array, may be {@code null}
 * @return The new array, {@code null} if both arrays are {@code null}.
 *      The type of the new array is the type of the first array,
 *      unless the first array is null, in which case the type is the same as the second array.
 * @since 2.1
 * @throws IllegalArgumentException if the array types are incompatible
 */
public static <T> T[] addAll(final T[] array1, final T... array2) {
    if (array1 == null) {
        return clone(array2);
    } else if (array2 == null) {
        return clone(array1);
    }
    final Class<?> type1 = array1.getClass().getComponentType();
    @SuppressWarnings("unchecked")
    // OK, because array is of type T
    final T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
    System.arraycopy(array1, 0, joinedArray, 0, array1.length);
    try {
        System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
    } catch (final ArrayStoreException ase) {
        // Check if problem was due to incompatible types
        /*
         * We do this here, rather than before the copy because:
         * - it would be a wasted check most of the time
         * - safer, in case check turns out to be too strict
         */
        final Class<?> type2 = array2.getClass().getComponentType();
        if (!type1.isAssignableFrom(type2)) {
            throw new IllegalArgumentException(
                    "Cannot store " + type2.getName() + " in an array of " + type1.getName(), ase);
        }
        throw ase; // No, so rethrow original
    }
    return joinedArray;
}

From source file:com.linecorp.armeria.server.docs.FunctionInfo.java

static FunctionInfo of(Method method, Map<Class<?>, ? extends TBase<?, ?>> sampleRequests,
        @Nullable String namespace, Map<String, String> docStrings) throws ClassNotFoundException {
    requireNonNull(method, "method");

    final String methodName = method.getName();

    final Class<?> serviceClass = method.getDeclaringClass().getDeclaringClass();
    final String serviceName = serviceClass.getName();
    final ClassLoader classLoader = serviceClass.getClassLoader();

    @SuppressWarnings("unchecked")
    Class<? extends TBase<?, ?>> argsClass = (Class<? extends TBase<?, ?>>) Class
            .forName(serviceName + '$' + methodName + "_args", false, classLoader);
    String sampleJsonRequest;/*w w  w .ja va  2s  . c  o m*/
    TBase<?, ?> sampleRequest = sampleRequests.get(argsClass);
    if (sampleRequest == null) {
        sampleJsonRequest = "";
    } else {
        TSerializer serializer = new TSerializer(ThriftProtocolFactories.TEXT);
        try {
            sampleJsonRequest = serializer.toString(sampleRequest, StandardCharsets.UTF_8.name());
        } catch (TException e) {
            throw new IllegalArgumentException(
                    "Failed to serialize to a memory buffer, this shouldn't ever happen.", e);
        }
    }

    @SuppressWarnings("unchecked")
    final FunctionInfo function = new FunctionInfo(namespace, methodName, argsClass,
            (Class<? extends TBase<?, ?>>) Class.forName(serviceName + '$' + methodName + "_result", false,
                    classLoader),
            (Class<? extends TException>[]) method.getExceptionTypes(), sampleJsonRequest, docStrings);
    return function;
}