public class AsOperator {
public static <T> T as(Object object, Class<T> 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");
}
}
}