Example usage for java.lang Class asSubclass

List of usage examples for java.lang Class asSubclass

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public <U> Class<? extends U> asSubclass(Class<U> clazz) 

Source Link

Document

Casts this Class object to represent a subclass of the class represented by the specified class object.

Usage

From source file:com.netflix.simianarmy.aws.AbstractRecorder.java

/**
 * Value to enum. Converts a "name|type" string back to an enum.
 *
 * @param value/*from ww  w.  j  a  va2s .  c  o  m*/
 *            the value
 * @return the enum
 */
@SuppressWarnings("unchecked")
protected static Enum valueToEnum(String value) {
    // parts = [enum value, enum class type]
    String[] parts = value.split("\\|", 2);
    if (parts.length < 2) {
        throw new RuntimeException("value " + value + " does not appear to be an internal enum format");
    }

    Class enumClass;
    try {
        enumClass = Class.forName(parts[1]);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("class for enum value " + value + " not found");
    }
    if (enumClass.isEnum()) {
        final Class<? extends Enum> enumSubClass = enumClass.asSubclass(Enum.class);
        return Enum.valueOf(enumSubClass, parts[0]);
    }
    throw new RuntimeException("value " + value + " does not appear to be an enum type");
}

From source file:org.apache.bookkeeper.common.util.ReflectionUtils.java

/**
 * Returns the {@code Class} object object associated with the class or interface
 * with the given string name, which is a subclass of {@code xface}.
 *
 * @param className class name//  www.java  2 s.  com
 * @param xface class interface
 * @return the class object associated with the class or interface with the given string name.
 */
public static <T> Class<? extends T> forName(String className, Class<T> xface) {

    // Construct the class
    Class<?> theCls;
    try {
        theCls = Class.forName(className);
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException(cnfe);
    }
    if (!xface.isAssignableFrom(theCls)) {
        throw new RuntimeException(className + " not " + xface.getName());
    }
    return theCls.asSubclass(xface);
}

From source file:org.apache.pulsar.sql.presto.PulsarConnectorUtils.java

/**
 * Create an instance of <code>userClassName</code> using provided <code>classLoader</code>.
 * This instance should implement the provided interface <code>xface</code>.
 *
 * @param userClassName user class name// w  w  w . j  av a 2s.  c  o m
 * @param xface the interface that the reflected instance should implement
 * @param classLoader class loader to load the class.
 * @return the instance
 */
public static <T> T createInstance(String userClassName, Class<T> xface, ClassLoader classLoader) {
    Class<?> theCls;
    try {
        theCls = Class.forName(userClassName, true, classLoader);
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException("User class must be in class path", cnfe);
    }
    if (!xface.isAssignableFrom(theCls)) {
        throw new RuntimeException(userClassName + " not " + xface.getName());
    }
    Class<T> tCls = (Class<T>) theCls.asSubclass(xface);
    try {
        Constructor<T> meth = tCls.getDeclaredConstructor();
        return meth.newInstance();
    } catch (InstantiationException ie) {
        throw new RuntimeException("User class must be concrete", ie);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException("User class must have a no-arg constructor", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("User class must a public constructor", e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException("User class constructor throws exception", e);
    }
}

From source file:org.apache.bookkeeper.common.util.ReflectionUtils.java

/**
 * Create an object using the given class name.
 *
 * @param clsName//from  www .j a  va  2  s . c  o m
 *          class name of which an object is created.
 * @param xface
 *          The interface implemented by the named class.
 * @return a new object
 */
@SuppressWarnings("unchecked")
public static <T> T newInstance(String clsName, Class<T> xface) {
    Class<?> theCls;
    try {
        theCls = Class.forName(clsName);
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException(cnfe);
    }
    if (!xface.isAssignableFrom(theCls)) {
        throw new RuntimeException(clsName + " not " + xface.getName());
    }
    return newInstance(theCls.asSubclass(xface));
}

From source file:com.medallia.spider.api.DynamicInputImpl.java

private static Object parseSingleValue(Class<?> rt, String v, AnnotatedElement anno,
        Map<Class<?>, InputArgParser<?>> inputArgParsers) {
    if (rt.isEnum()) {
        String vlow = v.toLowerCase();
        for (Enum e : rt.asSubclass(Enum.class).getEnumConstants()) {
            if (e.name().toLowerCase().equals(vlow))
                return e;
        }/* w  w  w  . j  a v  a 2  s.  co  m*/
        throw new AssertionError("Enum constant not found: " + v);
    } else if (rt == Integer.class) {
        // map blank strings to null
        return Strings.hasContent(v) ? Integer.valueOf(v) : null;
    } else if (rt == Integer.TYPE) {
        // primitive int must have a value
        return Integer.valueOf(v);
    } else if (rt == Long.class) {
        // map blank strings to null
        return Strings.hasContent(v) ? Long.valueOf(v) : null;
    } else if (rt == Long.TYPE) {
        // primitive long must have a value
        return Long.valueOf(v);
    } else if (rt == Double.class) {
        // map blank strings to null
        return Strings.hasContent(v) ? Double.valueOf(v) : null;
    } else if (rt == Double.TYPE) {
        // primitive double must have a value
        return Double.valueOf(v);
    } else if (rt == String.class) {
        return v;
    } else if (rt.isArray()) {
        Input.List ann = anno.getAnnotation(Input.List.class);
        if (ann == null)
            throw new AssertionError("Array type but no annotation (see " + Input.class + "): " + anno);
        String separator = ann.separator();
        String[] strVals = v.split(separator, -1);
        Class<?> arrayType = rt.getComponentType();
        Object a = Array.newInstance(arrayType, strVals.length);
        for (int i = 0; i < strVals.length; i++) {
            Array.set(a, i, parseSingleValue(arrayType, strVals[i], anno, inputArgParsers));
        }
        return a;
    } else if (inputArgParsers != null) {
        InputArgParser<?> argParser = inputArgParsers.get(rt);
        if (argParser != null) {
            return argParser.parse(v);
        }
    }
    throw new AssertionError("Unknown return type " + rt + " (val: " + v + ")");
}

From source file:org.apache.accumulo.test.util.SerializationUtil.java

/**
 * Create a new instance of a class whose name is given, as a descendent of a given subclass.
 *///from   w ww.  j  a  v  a2s .c  om
public static <E> E subclassNewInstance(String classname, Class<E> parentClass) {
    Class<?> c;
    try {
        c = Class.forName(classname);
    } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException("Can't find class: " + classname, e);
    }
    Class<? extends E> cm;
    try {
        cm = c.asSubclass(parentClass);
    } catch (ClassCastException e) {
        throw new IllegalArgumentException(classname + " is not a subclass of " + parentClass.getName(), e);
    }
    try {
        return cm.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new IllegalArgumentException("can't instantiate new instance of " + cm.getName(), e);
    }
}

From source file:com.jhkt.playgroundArena.db.nosql.mongodb.beans.AbstractDocument.java

private final static Object convertBacktoClassInstanceHelper(DBObject dBObject) {

    Object returnValue = null;/* www  . j a va  2 s .co m*/

    try {
        String className = dBObject.get(JPAConstants.CONVERTER_CLASS.CLASS.name()).toString();
        Class<?> classCheck = Class.forName(className);

        if (AbstractDocument.class.isAssignableFrom(classCheck)) {
            Class<? extends AbstractDocument> classToConvertTo = classCheck.asSubclass(AbstractDocument.class);
            AbstractDocument dInstance = classToConvertTo.newInstance();

            for (String key : dBObject.keySet()) {
                Object value = dBObject.get(key);

                char[] propertyChars = key.toCharArray();
                String methodMain = String.valueOf(propertyChars[0]).toUpperCase() + key.substring(1);
                String methodName = "set" + methodMain;
                String getMethodName = "get" + methodMain;

                if (key.equals(JPAConstants.CONVERTER_CLASS.CLASS.name())) {
                    continue;
                }

                if (value instanceof BasicDBObject) {
                    value = convertBacktoClassInstanceHelper(BasicDBObject.class.cast(value));
                }

                try {
                    Method getMethod = classToConvertTo.getMethod(getMethodName);
                    Class<?> getReturnType = getMethod.getReturnType();
                    Method method = classToConvertTo.getMethod(methodName, getReturnType);

                    if (getMethod.isAnnotationPresent(IDocumentKeyValue.class)) {
                        method.invoke(dInstance, value);
                    }
                } catch (NoSuchMethodException nsMe) {
                    _log.warn("Within convertBacktoClassInstance, following method was not found " + methodName,
                            nsMe);
                }

            }

            returnValue = dInstance;

        } else if (Enum.class.isAssignableFrom(classCheck)) {

            List<?> constants = Arrays.asList(classCheck.getEnumConstants());
            String name = String.class.cast(dBObject.get(JPAConstants.CONVERTER_CLASS.CONTENT.name()));
            for (Object constant : constants) {
                if (constant.toString().equals(name)) {
                    returnValue = constant;
                }
            }

        } else if (Collection.class.isAssignableFrom(classCheck)) {

            @SuppressWarnings("unchecked")
            Class<? extends Collection<? super Object>> classToConvertTo = (Class<? extends Collection<? super Object>>) classCheck;
            Collection<? super Object> cInstance = classToConvertTo.newInstance();

            BasicDBList bDBList = (BasicDBList) dBObject.get(JPAConstants.CONVERTER_CLASS.CONTENT.name());
            cInstance.addAll(bDBList);

            returnValue = cInstance;

        } else if (Map.class.isAssignableFrom(classCheck)) {

            @SuppressWarnings("unchecked")
            Class<? extends Map<String, ? super Object>> classToConvertTo = (Class<? extends Map<String, ? super Object>>) classCheck;
            Map<String, ? super Object> mInstance = classToConvertTo.newInstance();

            BasicDBObject mapObject = (BasicDBObject) dBObject.get(JPAConstants.CONVERTER_CLASS.CONTENT.name());
            mInstance.putAll(mapObject);

            returnValue = mInstance;

        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return returnValue;
}

From source file:org.apache.hadoop.io.compress.CompressionCodecFactory.java

/**
 * Get the list of codecs listed in the configuration
 * @param conf the configuration to look in
 * @return a list of the Configuration classes or null if the attribute
 *         was not set/*from   w ww .  j av  a2  s  . c o m*/
 */
public static List<Class<? extends CompressionCodec>> getCodecClasses(Configuration conf) {
    String codecsString = conf.get("io.compression.codecs");
    if (codecsString != null) {
        List<Class<? extends CompressionCodec>> result = new ArrayList<Class<? extends CompressionCodec>>();
        StringTokenizer codecSplit = new StringTokenizer(codecsString, ",");
        while (codecSplit.hasMoreElements()) {
            String codecSubstring = codecSplit.nextToken();
            if (codecSubstring.length() != 0) {
                try {
                    Class<?> cls = conf.getClassByName(codecSubstring);
                    if (!CompressionCodec.class.isAssignableFrom(cls)) {
                        throw new IllegalArgumentException(
                                "Class " + codecSubstring + " is not a CompressionCodec");
                    }
                    result.add(cls.asSubclass(CompressionCodec.class));
                } catch (ClassNotFoundException ex) {
                    throw new IllegalArgumentException("Compression codec " + codecSubstring + " not found.",
                            ex);
                }
            }
        }
        return result;
    } else {
        return null;
    }
}

From source file:net.femtoparsec.jnlmin.utils.ReflectUtils.java

public static int findClassDistance(Class<?> lower, Class<?> upper) {
    lower = boxClass(lower);//from w  w w  . ja  va 2s .c o m
    upper = boxClass(upper);

    if (lower == upper) {
        return 0;
    }

    if (Number.class.isAssignableFrom(lower) && Number.class.isAssignableFrom(upper)) {
        Integer lowerDistance = NUMBER_DISTANCE_MAP.get(lower.asSubclass(Number.class));
        Integer upperDistance = NUMBER_DISTANCE_MAP.get(upper.asSubclass(Number.class));
        if (lowerDistance != null && upperDistance != null) {
            if (lowerDistance > upperDistance) {
                return -1;
            }
            return upperDistance - lowerDistance;
        }
        //lower or upper is a custom Number (like BigInteger)
        //handle it as normal classes
    }

    if (!upper.isAssignableFrom(lower)) {
        return -1;
    }

    if (upper.isInterface()) {
        if (lower.isInterface()) {
            return findIIDistance(lower, upper);
        } else {
            return findCIDistance(lower, upper);
        }
    } else {
        assert !lower.isInterface();
        return findCCDistance(lower, upper);
    }

}

From source file:org.apache.bookkeeper.meta.AbstractZkLedgerManagerFactory.java

private static Class<? extends LedgerManagerFactory> resolveShadedLedgerManagerFactory(String lmfClassName,
        String shadedClassPrefix) throws ClassNotFoundException, IOException {
    if (null == lmfClassName) {
        return null;
    } else {/*from   w w  w  .  j a  v  a  2s  .c o  m*/
        // this is to address the issue when using the dlog shaded jar
        Class<?> theCls = Class.forName(shadedClassPrefix + lmfClassName);
        if (!LedgerManagerFactory.class.isAssignableFrom(theCls)) {
            throw new IOException("Wrong shaded ledger manager factory : " + shadedClassPrefix + lmfClassName);
        }
        return theCls.asSubclass(LedgerManagerFactory.class);
    }
}