Please note that all the code is a simplified example to convey only the basic ideas of my question. It should compile and run, although after a little editing.
I have several classes that implement a common interface.
public interface Inter{} public class Inter1 implements Inter{} public class Inter2 implements Inter{}
In a separate class, I have a list of Inter types that I use to store and delete Inter1 and Inter2 types based on user input.
java.util.ArrayList<Inter> inters = new java.util.ArrayList<Inter>();
I also have many overloaded methods that relate to how each implementation interacts with each other, along with the default implementation for 2 "Inter" s.
void doSomething(Inter in1, Inter in2){ System.out.println("Inter/Inter"); } void doSomething(Inter1 in1, Inter1 in2){ System.out.println("Inter1/Inter11"); } void doSomething(Inter2 in1, Inter1 in2){ System.out.println("Inter2/Inter1"); }
Methods are periodically called like this:
for(int i = 0; i < inters.size() - 1; i++){ for(int o = i+1; o < inters.size(); o++){ Inter in1 = inters.get(i); Inter in2 = inters.get(o); doSomething(in1.getClass().cast(in1), in2.getClass().cast(in2)); System.out.println("Class 1: " + in1.getClass().getName()); System.out.println("Class 2: " + in2.getClass().getName()); } }
Example output from this:
Inter/Inter Class 1: Inter Class 2: Inter Inter/Inter Class 1: Inter Class 2: Inter1 Inter/Inter Class 1: Inter1 Class 2: Inter1
Looking at the exit, it is clear that doSomething (Inter in1, Inter in2) is called even when other methods need to be called. Interestingly, the class names returned are correct.
Why does Java have static method overloads when class types are defined at runtime using reflection? Is there a way to get Java to do this? I know that I can use reflection both Class.getMethod () and method.invoke () to get the results I want, but it would be so neat to do this when casting.
I understand that questions about such concepts have been asked before, but so far all the answers have been informative, no one has satisfied me. Duplicate sending looked like it would work, but that would mean processing a lot of code, as I often use this type of thing.