Example usage for java.lang Object getClass

List of usage examples for java.lang Object getClass

Introduction

In this page you can find the example usage for java.lang Object getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:Main.java

/** Adds a click listener to the given view which invokes the method named by methodName on the given target.
 * The method must be public and take no arguments.
 *//* www .  j a  va  2 s  .c o  m*/
public static void bindOnClickListener(final Object target, View view, String methodName) {
    final Method method;
    try {
        method = target.getClass().getMethod(methodName);
    } catch (Exception ex) {
        throw new IllegalArgumentException(ex);
    }
    view.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                method.invoke(target);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    });
}

From source file:Main.java

/**
 * invoke the leftParameter and get the name property.
 * it will try the Array.length() and Map.get(),
 * then it will try get'Name' and is'Name',
 * last, it will to find the name by invoke field.
 *///from  ww w  .ja va2s.  c  om
public static Object searchProperty(Object leftParameter, String name) throws Exception {
    Class<?> leftClass = leftParameter.getClass();
    Object result;
    if (leftParameter.getClass().isArray() && "length".equals(name)) {
        result = Array.getLength(leftParameter);
    } else if (leftParameter instanceof Map) {
        result = ((Map<Object, Object>) leftParameter).get(name);
    } else {
        try {
            String getter = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
            Method method = leftClass.getMethod(getter, new Class<?>[0]);
            if (!method.isAccessible()) {
                method.setAccessible(true);
            }
            result = method.invoke(leftParameter, new Object[0]);
        } catch (NoSuchMethodException e2) {
            try {
                String getter = "is" + name.substring(0, 1).toUpperCase() + name.substring(1);
                Method method = leftClass.getMethod(getter, new Class<?>[0]);
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }
                result = method.invoke(leftParameter, new Object[0]);
            } catch (NoSuchMethodException e3) {
                Field field = leftClass.getField(name);
                result = field.get(leftParameter);
            }
        }
    }
    return result;
}

From source file:com.erinors.hpb.tests.HpbTestUtils.java

public static void assertEqualsByCloneableFields(Object o1, Object o2) {
    if (o1 == null || o2 == null || o1.getClass() != o2.getClass()) {
        throw new IllegalArgumentException(
                "Non-null objects of same class expected but got: " + o1 + ", " + o2);
    }//w  w w .  ja v a2  s. c o m

    List<Field> fields = new LinkedList<Field>();
    ClassUtils.collectCloneableFields(o1.getClass(), fields);

    for (Field field : fields) {
        try {
            ReflectionUtils.makeAccessible(field);

            Object fieldValue1 = field.get(o1);
            Object fieldValue2 = field.get(o2);

            if (!equal(fieldValue1, fieldValue2)) {
                throw new AssertionError("Field value mismatch: " + field + ", value1=" + fieldValue1
                        + ", value2=" + fieldValue2);
            }
        } catch (Exception e) {
            throw new RuntimeException("Cannot copy field: " + field, e);
        }
    }
}

From source file:io.pivotal.spring.xd.jdbcgpfdist.TestUtils.java

@SuppressWarnings("unchecked")
public static <T> T callMethod(String name, Object target) throws Exception {
    Class<?> clazz = target.getClass();
    Method method = ReflectionUtils.findMethod(clazz, name);

    if (method == null)
        throw new IllegalArgumentException(
                "Cannot find method '" + method + "' in the class hierarchy of " + target.getClass());
    method.setAccessible(true);// ww  w  . j  av  a2  s  .  c o m
    return (T) ReflectionUtils.invokeMethod(method, target);
}

From source file:com.nesscomputing.config.ConfigMagicDynamicMBean.java

private static Map<String, Object> toMap(Object configBean) {
    PropertyDescriptor[] props = ReflectUtils.getBeanGetters(configBean.getClass());

    Map<String, Object> result = Maps.newHashMap();

    for (PropertyDescriptor prop : props) {
        if (CONFIG_MAGIC_CALLBACKS_NAME.equals(prop.getName())) {
            continue;
        }// ww  w  . j av  a  2s  .c  o  m

        try {
            result.put(prop.getName(), ObjectUtils.toString(prop.getReadMethod().invoke(configBean), null));
        } catch (Exception e) {
            LOG.error(String.format("For class %s, unable to find config property %s", configBean.getClass(),
                    prop), e);
        }
    }

    return result;
}

From source file:Main.java

public static Object getFieldValue(Object object, String fieldName) {
    try {//from   w  w w.  ja  v  a  2  s. c om
        final Field field = getField(object.getClass(), fieldName);
        if (field == null) {
            throw new IllegalArgumentException("No field '" + fieldName + "' found in "
                    + object.getClass().getName() + " or its super classes");
        }
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        return field.get(object);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static Object getStaticVariable(Object obj, String str) {
    try {/*  w w  w  .j a  v a 2 s.  c o m*/
        obj.getClass().getDeclaredField(str).get(obj);
    } catch (NoSuchFieldException e) {
    } catch (IllegalAccessException i) {
    }
    return null;
}

From source file:Main.java

public static void setField(Object object, String fieldName, Object fieldValue) {
    Class<?> objectClass = object.getClass();
    if (objectClass != null) {
        try {/*from   w ww. j a v  a  2s. co m*/
            Field field = objectClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            Type type = field.getGenericType();

            //This is bad, but dear God I can't figure out how to convert a runtime Type to its actual type through reflection. I know how in C#....
            if (type.toString().toLowerCase().contains("short")) {
                fieldValue = Short.parseShort((String) fieldValue);
            }

            else if (type.toString().toLowerCase().contains("integer")) {
                fieldValue = Integer.parseInt((String) fieldValue);
            }

            else if (type.toString().toLowerCase().contains("long")) {
                fieldValue = Long.parseLong((String) fieldValue);
            }

            else if (type.toString().toLowerCase().contains("boolean")) {
                fieldValue = "1".equals(fieldValue); //Java, you're the worst language. And SQLite isn't helping.
            }

            field.set(object, fieldValue);
        }

        catch (NoSuchFieldException e) {
            return;
        }

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

From source file:Main.java

/**
 * Check if the object has a class to avoid
 * @param object Object to check//  w w  w.j  av a 2s.  c  om
 * @param avoidClasses Class[] list of classes to avoid
 * @return boolean TRUE if the class is in the list, FALSE to continue
 */
private static boolean isObjectToAvoid(Object object, Class[] avoidClasses) {
    if (object != null && avoidClasses != null) {
        Class objectClass = object.getClass();
        do {
            for (Class klass : avoidClasses) {
                if (objectClass.equals(klass)) {
                    return true;
                }
            }
            objectClass = objectClass.getSuperclass();
        } while (objectClass != null);
    }
    //not found
    return false;
}

From source file:com.codeabovelab.dm.common.utils.PojoBeanUtils.java

/**
 * Copy properties into lombok-style builders (it builder do not follow java bean convention)
 * @param src source bean object/*  w ww .  j a va2  s  .  c o m*/
 * @param dst destination builder object
 * @return dst object
 */
public static <T> T copyToBuilder(Object src, T dst) {
    PojoClass srcpojo = new PojoClass(src.getClass());
    Class<?> builderClass = dst.getClass();
    Method[] methods = builderClass.getMethods();
    for (Method method : methods) {
        boolean isBuilderSetter = method.getReturnType().equals(builderClass)
                && method.getParameterCount() == 1;
        if (!isBuilderSetter) {
            continue;
        }
        String propertyName = method.getName();
        Property property = srcpojo.getProperties().get(propertyName);
        if (property == null) {
            continue;
        }
        Object val = property.get(src);
        if (val == null) {
            continue;
        }
        try {
            method.invoke(dst, val);
        } catch (Exception e) {
            //nothing
        }
    }
    return dst;
}