Java Object Create as(Class cls, Object o)

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

Description

Returns the specified object as the specified class or returns null if the cast is not supported.

License

Open Source License

Parameter

Parameter Description
cls The generic class to cast the object to.
o The object to cast.
T The generic class to cast the object to.

Return

The object cast to the specified class or null if the cast is not supported.

Declaration

public static <T> T as(Class<T> cls, Object o) 

Method Source Code

//package com.java2s;
/*//from   ww w  .j  av  a2  s .c  o m
 * The contents of this file are subject to the OpenMRS Public License
 * Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */

public class Main {
    /**
     * Returns the specified object as the specified class or returns null if the cast is not supported.
     * @param cls The generic class to cast the object to.
     * @param o The object to cast.
     * @param <T> The generic class to cast the object to.
     * @return The object cast to the specified class or {@code null} if the cast is not supported.
     */
    public static <T> T as(Class<T> cls, Object o) {
        if (cls.isInstance(o)) {
            return cls.cast(o);
        }
        return null;
    }
}

Related

  1. as(Class clazz, I instance)
  2. as(Class t, Object o)
  3. as(Class targetClass, Object entity)
  4. as(Class type, Object value)
  5. as(Class type, U o)