wenn Sie einen Objektverweis für einige Klasse zum Beispiel Klasse abgeleitet von View.class
View someView <- by findViewById(int), getView(), getRootView() etc // any method that return view
Sie können überprüfen, ob Sie es auf eine andere Klasse von einem Up Cast zuweisen können - auf diese Weise durch Bewegung von rechts nach links (einige Beispiele unten):
EditText <- TextView <- View
FrameLayout <- ViewGroup <- View
NumberPicker <- LinearLayou <- ViewGroup <- View
Beispielanwendung:
// get View class reference by call to find view by id
View view = findViewById(R.id.someView);
if(view!=null) {
Class viewClass = view.getClass()
// check if we can assign edit text class to this class ???
if(EditText.class.isAssingableFrom(viewClass)) {
// u can cast it to edit text and do some stuff with edit text class as we did up casting while in this case it is allowed:
EditText editText = (EditText) view;
editText.setText(String);
}
}
diese Art und Weise werden wir nicht eine Ausnahme steigen, wenn wir zum Beispiel ohne Kontrolle diese Art von Guss tun:
((EditText) view).setText(String);
wenn Ansichtsklasse ist Typ anderes als EditText oder nicht von bearbeiten Textklasse Ausnahme abgeleitet wird geworfen werden.
aus der Klasse Umsetzung:
public final class Class<T> implements Serializable, AnnotatedElement, GenericDeclaration, Type {
...
/**
* Can {@code c} be assigned to this class? For example, String can be assigned to Object
* (by an upcast), however, an Object cannot be assigned to a String as a potentially exception
* throwing downcast would be necessary. Similarly for interfaces, a class that implements (or
* an interface that extends) another can be assigned to its parent, but not vice-versa. All
* Classes may assign to themselves. Classes for primitive types may not assign to each other.
*
* @param c the class to check.
* @return {@code true} if {@code c} can be assigned to the class
* represented by this {@code Class}; {@code false} otherwise.
* @throws NullPointerException if {@code c} is {@code null}.
*/
public boolean isAssignableFrom(Class<?> c) {
siehe auch:
The Type Comparison Operator instanceof