Вот метод для запуска setName для всех экземпляров JComponent, содержащихся внутри объекта, с использованием Reflection. Он покажет ошибку переполнения стека, если внутри объекта есть циклические ссылки.
public static void assignComponentNames(Object obj) {
try {
Method getComponentsMethod = obj.getClass().getMethod("getComponents", new Class[]{});
if (null != getComponentsMethod){
try {
for (Component component : (Component[])(getComponentsMethod.invoke(obj))){
assignComponentNames(component);
}
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InvocationTargetException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
else {
System.out.println(obj.toString());
}
} catch (NoSuchMethodException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName(); //this is a different name, the reflection level name
Object fieldValue = null;
try {
fieldValue = field.get(obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (null == fieldValue) {
continue;
}
if (fieldValue instanceof JComponent) {
String currentComponentNameForFieldValue = ((JComponent) fieldValue).getName();
if (null == currentComponentNameForFieldValue){
System.out.println("null component name");
((JComponent) fieldValue).setName(fieldName); //this sets the name specially for JComponent
}
}
else if(fieldValue instanceof Collection){
for (Object subObject : ((Collection)fieldValue).toArray()) {
assignComponentNames(subObject);
}
}
}
}