Java is a strongly typed language, and each instance must have a specified type. In fact, Java types have two types of declarations and run-time types (which can be said to be static types and dynamic types, as appropriate). Weak-type languages such as Python are often called untyped, but this is not rigorous because each instance has its Run-time type. You just don't have to declare the type of an instance beforehand.
To invoke a method in an object, this method needs to exist in the declaring type. That is, you can only invoke a method that is defined in the parent class, even if the instance is a determined subtype:
List list = new ArrayList();
list.add("data"); // 在这里没问题
list.ensureCapacity(4); // 这里就不行了ensureCapacity() 只在ArrayList中才有。
If we were to invoke a method in the actual type, we would first convert it to the correct type. In this case, we can convert ArrayList to list because ArrayList implements the list interface. can also be checked at runtime dynamically, using the list instanceof ArrayList.
Extensible interface
Unfortunately, a class cannot always implement the interface you need to implement. This may be because it works for only a few situations, or it is a type in a library that is not associated, or the interface is later changed.
In this case, you can use iadaptable. You can change the type of iadaptable dynamically. Avoid direct type conversions using the following methods:
Object o = new ArrayList();
List list = (List)o;
We can do this:
IAdaptable adaptable = new ArrayList();
List list = (List)adaptable.getAdapter(java.util.List.class);
You can think of it as a type of dynamic transformation; We converted the adaptable to the list instance.
Why not direct conversion instead of using extra Getadapter ()? This mechanism allows us to transform the target class into an interface that is not implemented. For example, we might want to use HashMap as a List, although they are not compatible.
IAdaptable adaptable = new HashMap();
List list = (List)adaptable.getAdapter(java.util.List.class);
Implement Iadaptable
Most iadaptable implementations seem to want to construct the overlay of multiple if expressions for supporting types. If you want to implement Getadapter () for HashMap, you can do this:
public class HashMap implements IAdaptable {
public Object getAdapter(Class clazz) {
if (clazz == java.util.List.class) {
List list = new ArrayList(this.size());
list.addAll(this.values());
return list;
}
return null;
}
// ...
}
Returns a proxy to itself, not a direct conversion type. If you are requesting an unsupported type, you can return null directly to indicate failure, which is better than throwing an exception.