public interface Address {
public int getNo();
}
public interface User<T extends Address> {
public String getUsername();
public T getAddress();
}
public class AddressImpl implements Address {
private int no;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
}
public class UserImpl implements User<AddressImpl> {
private String username;
private AddressImpl addressImpl;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public AddressImpl getAddress() {
return addressImpl;
}
public void setAddress(AddressImpl addressImpl) {
this.addressImpl = addressImpl;
}
}
int getAddressMethodCount = 0;
for (Method method : UserImpl.class.getMethods()) {
if (method.getName().startsWith("getAddress")) {
getAddressMethodCount++;
}
}
would yield 2 for getAddressMethodCount
variable; why is this so?
Interfaces can be implemented by multiple classes. There is no rule that only one class can implement these. Interfaces provide abstraction to the java.
The getConstructors() method is used to get the public constructors of the class to which an object belongs. The getMethods() method is used to get the public methods of the class to which an object belongs. We can invoke a method through reflection if we know its name and parameter types.
Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.
It's the way covariant return types are implemented. javap -private
will show you more conveniently than reflection.
The subclass with have a synthetic bridge method that handles forwarding to the more specific method. As far the JVM is concerned methods have a name, a sequence of raw typed parameters and a raw type return. You can overload on return type in bytecode.
A System.err.println(mehtod.getReturnType());
should give you different results for the two methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With