Java:在 class 的实例上调用时,无法从静态上下文中引用非静态变量

Java: Non static variable cannot be referenced from static context when called on instance of class

注意:这不是 this 等问题的重复,因为这些问题试图在 class 上调用实例方法,而不是实例。我的是,我试图在一个实例上调用一个实例方法,但它仍然给出错误。

当您尝试调用 class 上的实例方法时,我遇到了 classic 错误。我的问题是我试图在实例上调用实例方法,但出现了该错误。我的代码是:

public class PixelsManipulation{

// Load in the image
private final BufferedImage img = getImage("strawberry.jpg");
Sequential sequentialGrayscaler = new Sequential(img, 2, 2);//img.getWidth(),img.getHeight());

public static void main(String[] args) {  

    // Sequential:
    long startTime = System.currentTimeMillis();

    sequentialGrayscaler.ConvertToGrayscale(); // error here
    // ... etc.
}

为什么会发生这种情况?我错过了什么很明显的东西吗?我已经声明了一个名为 sequentialGrayscaler 的 Sequential 实例,我正在尝试对其调用 .ConvertToGrayscale(),而不是 class 本身。

顺序代码是:

public class Sequential {
private int width, height; // Image params
private BufferedImage img;

// SEQUENTIAL
// Load an image from file into the code so we can do things to it

Sequential(BufferedImage image, int imageWidth, int imageHeight){
    img = image;
    width = imageWidth;
    height = imageHeight;
}

public void ConvertToGrayscale(){
// etc.

编辑:如果我注释掉图像并仅使用整数参数实例化 Sequential 对象,它就可以工作。所以问题一定与BufferedImage有关。

这是我用来读取图像的代码:

private static BufferedImage getImage(String filename) {
    try {
        InputStream in = getClass().getResourceAsStream(filename); // now the error is here
        return ImageIO.read(in);
    } catch (IOException e) {
        System.out.println("The image was not loaded. Is it there? Is the filepath correct?");
        System.exit(1);
    }
    return null;
}

最后一个我可以 "chase" 出错的地方是我创建 InputStream 的那一行。那里的错误是 "non static method getClass() cannot be referenced from a static context"。这是在将 Sequential 声明与 ConvertToGrayscale() 方法一起设为静态之后。这是在说:

private static BufferedImage img = getImage("strawberry.jpg");
private static Sequential sequentialGrayscaler = new Sequential(img, 2, 2);

并将 getImage() 设为静态(必须这样做,否则我在尝试创建 BufferedImage 时会收到错误消息)。

编辑:最终我只需要将我的 getImage() 方法从我的主 class 中移出并移到顺序 class 中。理想情况下我不想这样做,因为这可能意味着如果我想在其他 classes 中实现它们,我将有很多重复的 getImage() 方法,但至少它现在有效。

因为PixelsManipulationClass的imgsequentialGrayscaler对象都是非静态的。将它们更改为静态。

private static BufferedImage img = getImage("strawberry.jpg");
private static Sequential sequentialGrayscaler = new Sequential(img, 2, 2);

此外,您不能从静态方法中执行 getClass().getResourceAsStream(...)。请改用 class 的名称。

public class PixelsManipulation {

    /* Your Code Here */

    private static BufferedImage getImage(String filename) {
        try {
            /* Code Change */
            InputStream in = PixelsManipulation.class.getResourceAsStream(filename);
            return ImageIO.read(in);
        } catch (IOException e) {
            System.out.println("The image was not loaded. Is it there? Is the filepath correct?");
            System.exit(1);
        }
        return null;
    }
}

进行这些更改后它应该可以正常工作。