来自静态类的Java引用

来自静态类的Java引用,java,static,Java,Static,很抱歉,这个问题以前可能有人问过,但我找不到任何一个在上下文中能够特别适用于我的问题的答案,以便我应用解决方案 不管怎样,我正在开发一个使用文件的程序。更新该文件时,我希望它用当前变量替换文件变量。我设置了一个处理该文件的主类,然后设置了另一个具有侦听文件更新的不同线程的类。更新文件时,我希望更新主类中的变量 这意味着更新侦听器类必须具有主类的实例,但当我在更新侦听器类初始化期间尝试发送它时,会出现一条警告,表示无法从静态上下文引用主类 代码如下: 主类 package me.xeyler;

很抱歉,这个问题以前可能有人问过,但我找不到任何一个在上下文中能够特别适用于我的问题的答案,以便我应用解决方案

不管怎样,我正在开发一个使用文件的程序。更新该文件时,我希望它用当前变量替换文件变量。我设置了一个处理该文件的主类,然后设置了另一个具有侦听文件更新的不同线程的类。更新文件时,我希望更新主类中的变量

这意味着更新侦听器类必须具有主类的实例,但当我在更新侦听器类初始化期间尝试发送它时,会出现一条警告,表示无法从静态上下文引用主类

代码如下:

主类

package me.xeyler;

import com.sun.media.jfxmedia.logging.Logger;

import javax.swing.*;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;

import static java.nio.file.StandardWatchEventKinds.*;

/**
 * Created by Brigham on 10/19/2016.
 */
public class ViewerMain {

    static FileHandler fileHandler;
    static File skinFile;

    public static void main(String[] args) {

        boolean bool = false;

        fileHandler = new FileHandler(this);
        fileHandler.start();
        while(true) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(bool);
        }

    }

    public void setSkinFile(File skinFile) {
        this.skinFile = skinFile;
    }
}
package me.xeyler;

import com.sun.media.jfxmedia.logging.Logger;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;

import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;

/**
 * Created by Brigham on 10/19/2016.
 */
public class FileHandler implements Runnable {

    private Thread fileThread;
    private String threadName;
    WatchService watcher = null;
    private ViewerMain main;

    public FileHandler(ViewerMain main) {

        this.main = main;
        this.threadName = "FileThread";

    }

    public void watchFile(Path path) {

    }

    public void watchFile(File file) {

        watchFile(Paths.get(file.getPath()));

    }

    public void close() {
        try {
            watcher.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start () {
        if (fileThread == null) {
            System.out.println("Starting new thread...");
            fileThread = new Thread (this, threadName);
            fileThread.start();
            System.out.println("Started thread: " + threadName);
        }
    }

    @Override
    public void run() {

        System.out.println("Running thread...");

        Path dir = Paths.get(System.getProperty("user.home"),"documents");
        try {
            watcher = FileSystems.getDefault().newWatchService();
            WatchKey key = dir.register(watcher,
                    ENTRY_MODIFY);
        } catch (IOException x) {
            x.printStackTrace();
        }

        for (;;) {

            // wait for key to be signaled
            WatchKey key;
            try {
                key = watcher.take();
            } catch (InterruptedException x) {
                return;
            }

            for (WatchEvent<?> event: key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();

                // The filename is the
                // context of the event.
                WatchEvent<Path> ev = (WatchEvent<Path>)event;
                Path filename = ev.context();

                if (filename.endsWith("text.txt")) {
                    System.out.println("File has changed");
                    //TODO: Update File variable in ViewerMain
                    main.setSkinFile(filename.toFile());
                }

            }

            // Reset the key -- this step is critical if you want to
            // receive further watch events.  If the key is no longer valid,
            // the directory is inaccessible so exit the loop.
            boolean valid = key.reset();
            if (!valid) {
                // TODO: Handle inaccessible directory
                break;
            }
        }

    }
}
文件侦听器类

package me.xeyler;

import com.sun.media.jfxmedia.logging.Logger;

import javax.swing.*;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;

import static java.nio.file.StandardWatchEventKinds.*;

/**
 * Created by Brigham on 10/19/2016.
 */
public class ViewerMain {

    static FileHandler fileHandler;
    static File skinFile;

    public static void main(String[] args) {

        boolean bool = false;

        fileHandler = new FileHandler(this);
        fileHandler.start();
        while(true) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(bool);
        }

    }

    public void setSkinFile(File skinFile) {
        this.skinFile = skinFile;
    }
}
package me.xeyler;

import com.sun.media.jfxmedia.logging.Logger;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;

import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;

/**
 * Created by Brigham on 10/19/2016.
 */
public class FileHandler implements Runnable {

    private Thread fileThread;
    private String threadName;
    WatchService watcher = null;
    private ViewerMain main;

    public FileHandler(ViewerMain main) {

        this.main = main;
        this.threadName = "FileThread";

    }

    public void watchFile(Path path) {

    }

    public void watchFile(File file) {

        watchFile(Paths.get(file.getPath()));

    }

    public void close() {
        try {
            watcher.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start () {
        if (fileThread == null) {
            System.out.println("Starting new thread...");
            fileThread = new Thread (this, threadName);
            fileThread.start();
            System.out.println("Started thread: " + threadName);
        }
    }

    @Override
    public void run() {

        System.out.println("Running thread...");

        Path dir = Paths.get(System.getProperty("user.home"),"documents");
        try {
            watcher = FileSystems.getDefault().newWatchService();
            WatchKey key = dir.register(watcher,
                    ENTRY_MODIFY);
        } catch (IOException x) {
            x.printStackTrace();
        }

        for (;;) {

            // wait for key to be signaled
            WatchKey key;
            try {
                key = watcher.take();
            } catch (InterruptedException x) {
                return;
            }

            for (WatchEvent<?> event: key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();

                // The filename is the
                // context of the event.
                WatchEvent<Path> ev = (WatchEvent<Path>)event;
                Path filename = ev.context();

                if (filename.endsWith("text.txt")) {
                    System.out.println("File has changed");
                    //TODO: Update File variable in ViewerMain
                    main.setSkinFile(filename.toFile());
                }

            }

            // Reset the key -- this step is critical if you want to
            // receive further watch events.  If the key is no longer valid,
            // the directory is inaccessible so exit the loop.
            boolean valid = key.reset();
            if (!valid) {
                // TODO: Handle inaccessible directory
                break;
            }
        }

    }
}
package me.xeyler;
导入com.sun.media.jfxmedia.logging.Logger;
导入javax.swing.*;
导入java.awt.*;
导入java.io.File;
导入java.io.IOException;
导入java.nio.file.*;
导入静态java.nio.file.StandardWatchEventTypes.ENTRY\u MODIFY;
导入静态java.nio.file.StandardWatchEventTypes.OVERFLOW;
/**
*由Brigham于2016年10月19日创建。
*/
公共类FileHandler实现可运行{
私有线程fileThread;
私有字符串threadName;
WatchService watcher=null;
主要是私人观众;
公共文件处理程序(ViewerMain){
this.main=main;
this.threadName=“FileThread”;
}
公共void监视文件(路径){
}
公共void监视文件(文件){
watchFile(path.get(file.getPath());
}
公众假期结束(){
试一试{
watcher.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
公共无效开始(){
if(fileThread==null){
System.out.println(“启动新线程…”);
fileThread=新线程(这个,threadName);
fileThread.start();
System.out.println(“启动线程:+threadName”);
}
}
@凌驾
公开募捐{
System.out.println(“运行线程…”);
Path dir=Path.get(System.getProperty(“user.home”),“documents”);
试一试{
watcher=FileSystems.getDefault().newWatchService();
WatchKey key=dir.寄存器(watcher,
输入(修改);
}捕获(IOX异常){
x、 printStackTrace();
}
对于(;;){
//等待钥匙发出信号
监视键;
试一试{
key=watcher.take();
}捕捉(中断异常x){
返回;
}
for(WatchEvent事件:key.pollEvents()){
WatchEvent.Kind-Kind=event.Kind();
//文件名是
//事件的背景。
WatchEvent ev=(WatchEvent)事件;
路径文件名=ev.context();
if(filename.endsWith(“text.txt”)){
System.out.println(“文件已更改”);
//TODO:更新ViewerMain中的文件变量
main.setSkinFile(filename.toFile());
}
}
//重置键——如果您想重置,此步骤至关重要
//接收进一步的监视事件。如果密钥不再有效,
//目录不可访问,请退出循环。
布尔有效值=key.reset();
如果(!有效){
//TODO:处理不可访问的目录
打破
}
}
}
}

我想答案是显而易见的,但是谢谢你的耐心

如果我理解正确,您需要一个
ViewerMain
类的实例

不能在静态上下文中应用

public static void main(String[] args) {

    ViewerMain viewer = new ViewerMain(); // an instance
    fileHandler = new FileHandler(viewer);
同样适用于
skinFile

public File skinFile; // Remove static

public void setSkinFile(File skinFile) {
    this.skinFile = skinFile;
}

如果我理解正确,您需要一个
ViewerMain
类的实例

不能在静态上下文中应用

public static void main(String[] args) {

    ViewerMain viewer = new ViewerMain(); // an instance
    fileHandler = new FileHandler(viewer);
同样适用于
skinFile

public File skinFile; // Remove static

public void setSkinFile(File skinFile) {
    this.skinFile = skinFile;
}
您不能这样做:

public void setSkinFile(File skinFile) {
    this.skinFile = skinFile;
}
由于skinFile是静态的,所以最好将该属性设置为
publicstaticfileskinfile
然后直接从FileHandler访问属性:

ViewerMain.skinFile = filename.toFile()
假定它是一个静态属性,您不需要类的实例来访问它,您可以直接使用该类。

您不能这样做:

public void setSkinFile(File skinFile) {
    this.skinFile = skinFile;
}
由于skinFile是静态的,所以最好将该属性设置为
publicstaticfileskinfile
然后直接从FileHandler访问属性:

ViewerMain.skinFile = filename.toFile()
假设它是一个静态属性,您不需要类的实例来访问它,您可以直接使用该类