Advanced Type Handling
Reflection API
Reflection provides powerful runtime type introspection and manipulation:
public class ReflectionTypeDemo {
public void analyzeType(Object obj) {
Class<?> clazz = obj.getClass();
System.out.println("Class Name: " + clazz.getName());
System.out.println("Simple Name: " + clazz.getSimpleName());
// Inspect declared methods
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
System.out.println("Method: " + method.getName());
}
}
}
Type Hierarchies and Polymorphism
graph TD
A[Type Hierarchy] --> B[Inheritance]
A --> C[Interfaces]
A --> D[Abstract Classes]
Generics and Type Bounds
public class TypeBoundsDemo<T extends Comparable<T>> {
private T value;
public void compareValues(T other) {
if (value.compareTo(other) > 0) {
System.out.println("Current value is larger");
}
}
}
Advanced Type Checking Strategies
Strategy |
Description |
Use Case |
Reflection |
Runtime type analysis |
Dynamic type inspection |
Generics |
Compile-time type safety |
Type-safe collections |
Pattern Matching |
Simplified type checking |
Modern Java type handling |
Type Erasure and Generics
public class TypeErasureDemo {
// Generic method with type inference
public <T> void printTypeInfo(T item) {
System.out.println("Type: " + item.getClass().getTypeName());
}
// Bounded type parameters
public <T extends Number> double calculateSum(List<T> numbers) {
return numbers.stream()
.mapToDouble(Number::doubleValue)
.sum();
}
}
Custom Type Handling
public class CustomTypeHandler {
// Type-safe factory method
public static <T> T createInstance(Class<T> clazz) {
try {
return clazz.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException("Cannot create instance", e);
}
}
// Advanced type matching
public static <T> boolean isCompatibleType(Object obj, Class<T> expectedType) {
return expectedType.isInstance(obj);
}
}
Type Conversion Techniques
public class TypeConversionDemo {
// Safe type conversion
public <T> Optional<T> safeCast(Object obj, Class<T> type) {
return type.isInstance(obj)
? Optional.of(type.cast(obj))
: Optional.empty();
}
// Multiple type conversion strategies
public Object convertType(Object input, Class<?> targetType) {
if (targetType == String.class) {
return String.valueOf(input);
} else if (targetType == Integer.class) {
return Integer.parseInt(input.toString());
}
return null;
}
}
Advanced Type Matching
graph TD
A[Type Matching] --> B[Instanceof]
A --> C[Reflection]
A --> D[Pattern Matching]
A --> E[Generics]
Key Takeaways
- Leverage reflection for dynamic type analysis
- Use generics for compile-time type safety
- Implement flexible type conversion strategies
- Understand type erasure and its implications
- Utilize modern Java type handling techniques
Mastering advanced type handling is crucial for developing robust and flexible applications on platforms like LabEx, enabling more dynamic and type-safe code implementations.