Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does reflection return two methods, when there is only one implementation?

Suppose I have this code:

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;
    }
}

Running the code:

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?

like image 723
Random42 Avatar asked May 03 '13 14:05

Random42


People also ask

Do I need to use an interface when only one class will ever implement it?

Interfaces can be implemented by multiple classes. There is no rule that only one class can implement these. Interfaces provide abstraction to the java.

Which method is used to get methods using reflection?

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.

What is reflection and why is it useful in Java?

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.


1 Answers

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.

like image 138
Tom Hawtin - tackline Avatar answered Sep 18 '22 15:09

Tom Hawtin - tackline