Java Object Create as(Object o, Class clazz)

Here you can find the source of as(Object o, Class clazz)

Description

Attempts to cast to the specified type, returns null if not castable.

License

Open Source License

Parameter

Parameter Description
T a parameter
o a parameter
clazz a parameter

Declaration

@SuppressWarnings("unchecked")
public static <T> T as(Object o, Class<T> clazz) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*w  w  w .  j  a  v a2 s. c o m*/
     * Attempts to cast to the specified type, returns null if not castable. Useful with generics, and avoids spreading warnings throughout the code.
     * 
     * @param <T>
     * @param o
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T as(Object o, Class<T> clazz) {
        if (o == null)
            return null;
        if (!clazz.isAssignableFrom(o.getClass()))
            return null;
        return (T) o;
    }
}

Related

  1. as(Class type, Object value)
  2. as(Class type, U o)
  3. as(Object cst)
  4. as(Object instance, Class clazz)
  5. as(Object o)
  6. as(Object obj)
  7. as(Object value, Class c)
  8. as(Object value, Class type)
  9. toObject(boolean[] array)