Example usage for org.apache.commons.lang ClassUtils isAssignable

List of usage examples for org.apache.commons.lang ClassUtils isAssignable

Introduction

In this page you can find the example usage for org.apache.commons.lang ClassUtils isAssignable.

Prototype


public static boolean isAssignable(Class<?> cls, Class<?> toClass) 

Source Link

Document

Checks if one Class can be assigned to a variable of another Class.

Unlike the Class#isAssignableFrom(java.lang.Class) method, this method takes into account widenings of primitive classes and nulls.

Primitive widenings allow an int to be assigned to a long, float or double.

Usage

From source file:MainClass.java

public static void main(String[] args) {
    System.out.println("5) Every Object is an String = " + ClassUtils.isAssignable(Object.class, String.class));
}

From source file:ClassUtilsTrial.java

public static void main(String[] args) {
    System.out.println(//ww w .  j  ava2  s . co m
            "1) Interfaces implemented by java.lang.String >>> " + ClassUtils.getAllInterfaces(String.class));
    System.out
            .println("2) SuperClasses of java.lang.String >>> " + ClassUtils.getAllSuperclasses(String.class));
    System.out.println("3) PackageName of a string >>> " + ClassUtils.getPackageName("A String", "IfNull"));
    System.out.println("4) Every String is an Object = " + ClassUtils.isAssignable(String.class, Object.class));
    System.out.println("5) Every Object is an String = " + ClassUtils.isAssignable(Object.class, String.class));
}

From source file:com.yahoo.flowetl.commons.runner.Main.java

/**
 * The main method entry point./*  www  . j a va  2s.  co  m*/
 */
public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        System.out.println(
                Main.class.getSimpleName() + " [runner fully qualified java class name] arguments ...");
        return;
    }
    System.out.println("+Argument info:");
    StringBuilder argsStr = new StringBuilder();
    for (int i = 0; i < args.length; i++) {
        argsStr.append("(" + (i + 1) + ") " + args[i] + " [" + args[i].length() + " chars]");
        if (i + 1 != args.length) {
            argsStr.append(" ");
        }
    }
    System.out.println(argsStr);
    Map<String, Object> sysInfo = getRuntimeInfo();
    System.out.println("+Runtime info:");
    for (Entry<String, Object> e : sysInfo.entrySet()) {
        System.out.println("--- " + e.getKey() + " => " + (e.getValue() == null ? "" : e.getValue()));
    }
    String classToRun = args[0];
    Class<?> testToRun = KlassUtils.getClassForName(classToRun);
    if (KlassUtils.isAbstract(testToRun) || KlassUtils.isInterface(testToRun)) {
        System.out.println("+Runner class name that is not abstract or an interface is required!");
        return;
    }
    if (ClassUtils.isAssignable(testToRun, (Runner.class)) == false) {
        System.out.println("+Runner class name that is a instance/subclass of " + Runner.class.getSimpleName()
                + " is required!");
        return;
    }
    Class<Runner> rToRun = KlassUtils.getClassForName(classToRun);
    System.out.println("+Running program specified by runner class " + rToRun);
    Runner r = KlassUtils.getInstanceOf(rToRun, new Object[] {});
    String[] nargs = (String[]) ArrayUtils.subarray(args, 1, args.length);
    System.out.println("+Proxying to object " + r + " with arguments [" + StringUtils.join(nargs, ",") + "]");
    r.runProgram(nargs);
}

From source file:dk.teachus.frontend.utils.BookingTypeRenderer.java

@Override
public Object getDisplayValue(Class<? extends Booking> bookingClass) {
    String display = ""; //$NON-NLS-1$

    if (bookingClass != null) {
        if (ClassUtils.isAssignable(bookingClass, PupilBooking.class)) {
            display = TeachUsSession.get().getString("BookingType.pupil");
        } else if (ClassUtils.isAssignable(bookingClass, TeacherBooking.class)) {
            display = TeachUsSession.get().getString("BookingType.teacher");
        } else {/*w w  w .  j a  v  a2  s  .  c  o m*/
            throw new IllegalArgumentException("Unsupported booking type: " + bookingClass);
        }
    }

    return display;
}

From source file:com.ginema.api.reflection.ReflectionUtils.java

public static boolean isACollection(Object c) {
    return ClassUtils.isAssignable(c.getClass(), Collection.class);
}

From source file:com.swordlord.gozer.datatypeformat.DataTypeHelper.java

/**
 * Return compatible class for typedValue based on untypedValueClass 
 * /*from  ww w. ja  va2 s  .co  m*/
 * @param untypedValueClass
 * @param typedValue
 * @return
 */
public static Object fromDataType(Class<?> untypedValueClass, Object typedValue) {
    Log LOG = LogFactory.getLog(DataTypeHelper.class);

    if (typedValue == null) {
        return null;
    }

    if (untypedValueClass == null) {
        return typedValue;
    }

    if (ClassUtils.isAssignable(typedValue.getClass(), untypedValueClass)) {
        return typedValue;
    }

    String strTypedValue = null;
    boolean isStringTypedValue = typedValue instanceof String;

    Number numTypedValue = null;
    boolean isNumberTypedValue = typedValue instanceof Number;

    Boolean boolTypedValue = null;
    boolean isBooleanTypedValue = typedValue instanceof Boolean;

    Date dateTypedValue = null;
    boolean isDateTypedValue = typedValue instanceof Date;

    if (isStringTypedValue) {
        strTypedValue = (String) typedValue;
    }
    if (isNumberTypedValue) {
        numTypedValue = (Number) typedValue;
    }
    if (isBooleanTypedValue) {
        boolTypedValue = (Boolean) typedValue;
    }
    if (isDateTypedValue) {
        dateTypedValue = (Date) typedValue;
    }

    Object v = null;
    if (String.class.equals(untypedValueClass)) {
        v = ObjectUtils.toString(typedValue);
    } else if (BigDecimal.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createBigDecimal(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new BigDecimal(numTypedValue.doubleValue());
        } else if (isBooleanTypedValue) {
            v = new BigDecimal(BooleanUtils.toInteger(boolTypedValue.booleanValue()));
        } else if (isDateTypedValue) {
            v = new BigDecimal(dateTypedValue.getTime());
        }
    } else if (Boolean.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = BooleanUtils.toBooleanObject(strTypedValue);
        } else if (isNumberTypedValue) {
            v = BooleanUtils.toBooleanObject(numTypedValue.intValue());
        } else if (isDateTypedValue) {
            v = BooleanUtils.toBooleanObject((int) dateTypedValue.getTime());
        }
    } else if (Byte.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = Byte.valueOf(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Byte(numTypedValue.byteValue());
        } else if (isBooleanTypedValue) {
            v = new Byte((byte) BooleanUtils.toInteger(boolTypedValue.booleanValue()));
        } else if (isDateTypedValue) {
            v = new Byte((byte) dateTypedValue.getTime());
        }
    } else if (byte[].class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = strTypedValue.getBytes();
        }
    } else if (Double.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createDouble(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Double(numTypedValue.doubleValue());
        } else if (isBooleanTypedValue) {
            v = new Double(BooleanUtils.toInteger(boolTypedValue.booleanValue()));
        } else if (isDateTypedValue) {
            v = new Double(dateTypedValue.getTime());
        }
    } else if (Float.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createFloat(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Float(numTypedValue.floatValue());
        } else if (isBooleanTypedValue) {
            v = new Float(BooleanUtils.toInteger(boolTypedValue.booleanValue()));
        } else if (isDateTypedValue) {
            v = new Float(dateTypedValue.getTime());
        }
    } else if (Short.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createInteger(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Integer(numTypedValue.intValue());
        } else if (isBooleanTypedValue) {
            v = BooleanUtils.toIntegerObject(boolTypedValue.booleanValue());
        } else if (isDateTypedValue) {
            v = new Integer((int) dateTypedValue.getTime());
        }
    } else if (Integer.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createInteger(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Integer(numTypedValue.intValue());
        } else if (isBooleanTypedValue) {
            v = BooleanUtils.toIntegerObject(boolTypedValue.booleanValue());
        } else if (isDateTypedValue) {
            v = new Integer((int) dateTypedValue.getTime());
        }
    } else if (Long.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createLong(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Long(numTypedValue.longValue());
        } else if (isBooleanTypedValue) {
            v = new Long(BooleanUtils.toInteger(boolTypedValue.booleanValue()));
        } else if (isDateTypedValue) {
            v = new Long(dateTypedValue.getTime());
        }
    } else if (java.sql.Date.class.equals(untypedValueClass)) {
        if (isNumberTypedValue) {
            v = new java.sql.Date(numTypedValue.longValue());
        } else if (isDateTypedValue) {
            v = new java.sql.Date(dateTypedValue.getTime());
        }
    } else if (java.sql.Time.class.equals(untypedValueClass)) {
        if (isNumberTypedValue) {
            v = new java.sql.Time(numTypedValue.longValue());
        } else if (isDateTypedValue) {
            v = new java.sql.Time(dateTypedValue.getTime());
        }
    } else if (java.sql.Timestamp.class.equals(untypedValueClass)) {
        if (isNumberTypedValue) {
            v = new java.sql.Timestamp(numTypedValue.longValue());
        } else if (isDateTypedValue) {
            v = new java.sql.Timestamp(dateTypedValue.getTime());
        }
    } else if (Date.class.equals(untypedValueClass)) {
        if (isNumberTypedValue) {
            v = new Date(numTypedValue.longValue());
        } else if (isStringTypedValue) {
            try {
                v = DateFormat.getDateInstance().parse(strTypedValue);
            } catch (ParseException e) {
                LOG.error("Unable to parse the date : " + strTypedValue);
                LOG.debug(e.getMessage());
            }
        }
    }
    return v;
}

From source file:com.github.neio.filesystem.paths.AbstractPath.java

@SuppressWarnings("unchecked")
@Override/*from  w  ww  . j a  va2 s  .  c  o m*/
public int compareTo(Path o) {
    if (o != null) {
        if (ClassUtils.isAssignable(o.getClass(), clazz)) {
            return howDoICompare((P) o);
        } else {
            throw new ClassCastException(o.getClass() + " was not comparable with " + clazz.getName());
        }
    } else {
        throw new NullPointerException("Path being compared was null");
    }
}

From source file:com.github.neio.filesystem.paths.AbstractPath.java

@SuppressWarnings("unchecked")
@Override//from   w ww  .  j ava2 s .c o m
public boolean equals(Object obj) {
    if (obj != null) {
        if (ClassUtils.isAssignable(obj.getClass(), clazz) == true) {
            return amIEqual((P) obj);
        } else {
            return false;
        }
    } else {
        return false;
    }
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

/**
 * Returns a {@link Constructor} object that reflects the specified constructor of the given type.
 * <p/>//ww  w.  j a  v a  2 s  .  c  om
 * If no parameter types are specified i.e., {@code paramTypes} is {@code null} or empty, the default constructor
 * is returned.<br/>
 * If a parameter type is not known i.e., it is {@code null}, all declared constructors are checked whether their
 * parameter types conform to the known parameter types i.e., if every known type is assignable to the parameter
 * type of the constructor and if exactly one was found, it is returned.<br/>
 * Otherwise a {@link NoSuchMethodException} is thrown indicating that no or several constructors were found.
 *
 * @param type the class
 * @param paramTypes the full-qualified class names of the parameters (can be {@code null})
 * @param classLoader the class loader to use
 * @return the accessible constructor resolved
 * @throws NoSuchMethodException if there are zero or more than one constructor candidates
 * @throws ClassNotFoundException if a class cannot be located by the specified class loader
 */
@SuppressWarnings("unchecked")
public static <T> Constructor<T> findConstructor(Class<T> type, Class<?>... clazzes)
        throws NoSuchMethodException, ClassNotFoundException {
    Constructor<T> constructor = null;

    // If all parameter types are known, find the constructor that exactly matches the signature
    if (!ArrayUtils.contains(clazzes, null)) {
        try {
            constructor = type.getDeclaredConstructor(clazzes);
        } catch (NoSuchMethodException e) {
            // Ignore
        }
    }

    // If no constructor was found, find all possible candidates
    if (constructor == null) {
        List<Constructor<T>> candidates = new ArrayList<>(1);
        for (Constructor<T> declaredConstructor : (Constructor<T>[]) type.getDeclaredConstructors()) {
            if (ClassUtils.isAssignable(clazzes, declaredConstructor.getParameterTypes())) {

                // Check if there is already a constructor method with the same signature
                for (int i = 0; i < candidates.size(); i++) {
                    Constructor<T> candidate = candidates.get(i);
                    /**
                     * If all parameter types of constructor A are assignable to the types of constructor B
                     * (at least one type is a subtype of the corresponding parameter), keep the one whose types
                     * are more concrete and drop the other one.
                     */
                    if (ClassUtils.isAssignable(declaredConstructor.getParameterTypes(),
                            candidate.getParameterTypes())) {
                        candidates.remove(candidate);
                        i--;
                    } else if (ClassUtils.isAssignable(candidate.getParameterTypes(),
                            declaredConstructor.getParameterTypes())) {
                        declaredConstructor = null;
                        break;
                    }
                }

                if (declaredConstructor != null) {
                    candidates.add(declaredConstructor);
                }
            }
        }
        if (candidates.size() != 1) {
            throw new NoSuchMethodException(
                    String.format("Cannot find distinct constructor for type '%s' with parameter types %s",
                            type, Arrays.toString(clazzes)));
        }
        constructor = candidates.get(0);
    }

    //do we really need this dependency?
    //ReflectionUtils.makeAccessible(constructor);
    if (constructor != null && !constructor.isAccessible())
        constructor.setAccessible(true);

    return constructor;

}

From source file:com.ginema.api.enricher.SensitiveDataExtractor.java

/**
 * Recursive method to enrich the object
 * /*  ww w  .j  a v  a 2s  . c o  m*/
 * @param o
 * @param holder
 * @throws IllegalAccessException
 */
private static void enrichObjectTree(Object o, SensitiveDataHolder holder) throws Exception {
    for (Field f : o.getClass().getDeclaredFields()) {
        if (!ReflectionUtils.isPrimitive(f)) {
            Method getter = PropertyDescriptorHolder.getGetterMethod(o.getClass(), f.getName());
            if (getter == null && !java.lang.reflect.Modifier.isStatic(f.getModifiers())) {
                throw new IllegalArgumentException("No getter found for property " + f.getName());
            }
            if (getter == null)
                continue;
            Object value = getter.invoke(o, null);

            if (ClassUtils.isAssignable(f.getType(), SensitiveDataField.class)) {
                populateHolderMapByType(holder, (SensitiveDataField<?>) value);
            }
            checkAndEnrichObject(holder, value);
            checkAndEnrichCollection(holder, value);
        }
    }

}