1

I came across this code on Vogella which demonstrates creating a LabelProvider for a JFACE tree.

I'm finding it really confusing however. The Image objects, named FOLDER and FILE are defined by calling a method which returns either FOLDER or FILE.

Essentially it's like a dictionary saying insured means someone with insurance and insurance is what some who is insured has. I am confused.

Why doesn't it cause an infinite loop?

package de.vogella.jface.treeviewer.provider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import de.vogella.jface.treeviewer.model.Category;
import de.vogella.jface.treeviewer.model.Todo;

public class TodoLabelProvider extends LabelProvider {

  private static final Image FOLDER = getImage("folder.gif");
  private static final Image FILE = getImage("file.gif");


  @Override
  public String getText(Object element) {
    if (element instanceof Category) {
      Category category = (Category) element;
      return category.getName();
    }
    return ((Todo) element).getSummary();
  }

  @Override
  public Image getImage(Object element) {
    if (element instanceof Category) {
      return FOLDER;
    }
    return FILE;
  }

  // Helper Method to load the images
  private static Image getImage(String file) {
    Bundle bundle = FrameworkUtil.getBundle(TodoLabelProvider.class);
    URL url = FileLocator.find(bundle, new Path("icons/" + file), null);
    ImageDescriptor image = ImageDescriptor.createFromURL(url);
    return image.createImage();

  } 
} 
4

1 回答 1

4

由于方法重载,您感到困惑。这里的电话:

private static final Image FOLDER = getImage("folder.gif");
private static final Image FILE = getImage("file.gif");

不要调用此方法:

public Image getImage(Object element) {

他们称之为:

private static Image getImage(String file) {

他们无论如何都不能调用第一个方法,因为它是一个实例方法,并且调用是在一个静态字段初始化器中,没有实例可以调用该方法。但是他们还是调用了第二种方法,因为参数是一个字符串。

它仍然是很奇怪的代码——尤其是getImage(Object element).

即使是这样的:

// Bogus code!
private static Image FOLDER = getImage("folder.gif");
private static Image FILE = getImage("file.gif");

private static Image getImage(String name)
{
    return name.equals("FRED") ? FOLDER : FILE;
}

...这仍然不会导致无限循环。你最终会得到空值。静态字段初始化器只是设置变量的初始值。它不会将变量与方法调用相关联,因此对变量的任何访问都会调用该方法。

于 2013-05-24T14:48:42.953 回答