Java 实现一个类似 C# as 运算符的效果

public class AsOperator {

    public static  T as(Object object, Class targetClass) {
        if (targetClass.isInstance(object)) {
            return targetClass.cast(object);
        }
        
        return null;
    }

    public static void main(String[] args) {
        Object obj = "This is a string";
        
        // Test with matching type
        String result = as(obj, String.class);
        if (result != null) {
            System.out.println("Casted object: " + result);
        } else {
            System.out.println("Casting failed");
        }
        
        // Test with non-matching type
        Integer integerResult = as(obj, Integer.class);
        if (integerResult != null) {
            System.out.println("Casted object: " + integerResult);
        } else {
            System.out.println("Casting failed");
        }
    }
}

你可能感兴趣的:(java,c#,开发语言)