Reputation: 3
So I have a problem.My assingment untill tommorw is to make a java program,that gets a class,then writes its Name and methods,Then gets the one that it implements,does the same and continues up to Object.The problem is I have to make it so the methods don't repeat themselves.(Only the class that adds the method should print it out,the implementation of that class should no longer have it.) I made it so it prints everything only once,but it prints it out very strangely. Here is the code:
public static void main(String[] args) {
Object o = new JRadioButton();
Class cl;
HashSet methodsnames = new HashSet();
for (cl = o.getClass(); cl != null; cl = cl.getSuperclass()) {
HashSet al = new HashSet();
System.out.println(cl.getName()+ " - ");
for (Method m : cl.getMethods()){
boolean added = methodsnames.add(m.getName());
if(added){
al.add(m.getName());}
}
al.forEach(System.out::println);
System.out.println("=============================");
}
}
Upvotes: 0
Views: 47
Reputation: 2720
Use getDeclaredMethods
instead getMethods
:
import java.lang.*;
import java.lang.reflect.*;
import java.util.*;
import javax.swing.*;
public class main
{
public static void main(String ...args) {
Object o = new JRadioButton();
Class cl;
HashSet methodsnames = new HashSet();
for (cl = o.getClass(); cl != null; cl = cl.getSuperclass()) {
HashSet al = new HashSet();
System.out.println(cl.getName()+ " - ");
for (Method m : cl.getDeclaredMethods()){
boolean added = methodsnames.add(m.getName());
if(added){
al.add(m.getName());
}
}
al.forEach(System.out::println);
System.out.println("=============================");
}
}
}
Check this code runing on Ideone.
Upvotes: 0
Reputation: 1835
With Class#getMethods
you get all public methods of the class - even the public methods provided by its super-class.
I think you want to print the method only if the class also provides the implementation so you need to check the declaring class: m.getDeclaringClass().equals(cl)
Upvotes: 2