简体   繁体   English

无法从其他类访问公共实例

[英]Can not access public instances from other class

I have two instances: socket and packet as public in main class but I can not access them from other class, and they are in the same package.我有两个实例:socket 和 packet 在主类中作为 public,但我无法从其他类访问它们,并且它们在同一个包中。

I get: cannot find symbol for both of them.我得到:找不到他们两个的符号。

    public class enviar extends TimerTask {

    public void run() {    
           socket.send(packet);
    }

    }
    public class UDP_Client {

    public static DatagramSocket socket;
    static InetAddress address;
    public static DatagramPacket packet;

    public static void main(String args[]){


    final int puerto = 3000;

    try{   

    socket = new DatagramSocket();
    address = InetAddress.getByName("localhost");

    byte[] buf = payload.MSG.getBytes();
    packet = new DatagramPacket(buf, buf.length, address , puerto);

    while(true){
        Timer timer = new Timer();
        timer.schedule(new enviar(), 0, 50);
    }

    }catch(IOException e){
        System.out.println(e);
    }

    }
    }

Thanks mates!!谢谢小伙伴!!

The issue is that you are not telling Java where to find the socket and packet fields.问题是您没有告诉 Java 在哪里可以找到socketpacket字段。 If you specify the class that contains them, it will resolve your issue.如果您指定包含它们的类,它将解决您的问题。 Your code should look something like this:您的代码应如下所示:

UDP_Client.socket.send(UDP_Client.packet);

This will work, but you can also statically import the fields, in the enviar file, so that you don't need the class name identifier.这会起作用,但您也可以静态导入enviar文件中的字段,这样您就不需要类名标识符。

import static package.to.UDP_Client.socket;
import static package.to.UDP_Client.packet;

Then you could just leave your code as-is.然后你可以保持你的代码原样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM