通过局域网在其他Java应用程序上调用方法



我有 2 个 Java 应用程序通过 LAN(wifi 网络(相互连接

第一个服务器应用程序.java

public class ServerApp {
public static void zzz(){
    System.out.println("hi");
}
public static void main(String[] args) {
    try {
        ServerSocket ss=new ServerSocket(6666);
        Socket s=ss.accept();
        DataInputStream dis = new DataInputStream(s.getInputStream());
        String str =(String)dis.readUTF();
        System.out.print("message : "+str);
        ss.close();
    } catch (IOException e) {
        System.out.println(e);
    }
}
}

第二个客户端应用程序.java

public class ClientApp {
public static void main(String[] args) {
    try {
        Scanner in = new Scanner(System.in);
        System.out.print("send message to the server ?[y/n]:");
        String inputString=in.next();
        if ("y".equals(inputString)) {
            Socket s= new Socket("192.168.20.125", 6666);
            DataOutputStream dout=new DataOutputStream(s.getOutputStream());
            dout.writeUTF("hellow servern");
            dout.writeUTF("zzz");
            dout.flush();
            dout.close();
            s.close();
        } else if ("n".equals(inputString)) {
            System.out.println("exit");
        } else {
            System.out.println("error: you should enter a valid value");
        }
    } catch (IOException e) {
        System.out.println(e);
    }
}
}

发生的情况是,客户端应用程序使用服务器 IP 地址通过 LAN 向服务器应用程序发送消息 - 服务器应用程序有一个方法调用 zzz((,所以我想要的只是如何让客户端应用程序调用此方法(如果可能(

谢谢

@MichalLonski如何使"obj"向服务器应用程序指示

由于这是static方法,因此您必须指出ServerApp.class,如下所示:

public class ServerApp {
    public static void zzz() {
        System.out.println("hi");
    }
    public static void main(String[] args) throws Exception {
        String methodName = "zzz";
        java.lang.reflect.Method method = ServerApp.class.getMethod(methodName);
        method.invoke(ServerApp.class);
    }
}

您可以将其更改为不使用静态方法,而是使用实例方法。为此,您必须创建ServerApp类的实例,如下所示:

public class ServerApp {
    public void foo() {
        System.out.println("Hello there from non static method!");
    }
    public static void main(String[] args) throws Exception {
        String methodName = "foo";
        ServerApp app = new ServerApp();
        java.lang.reflect.Method method = app.getClass().getMethod(methodName);
        method.invoke(app);
    }
}

编辑

如果还想指定要调用的方法的类,可以这样操作:

package com.example;
class Foo {
    public static void bar() {
        System.out.println("Hello there.");
    }
}
public class ServerApp {
    public static void main(String[] args) throws Exception {
        //read the class and method name from the socket
        String className = "com.example.Foo";
        String methodName = "bar";
        Class<?> clazz = Class.forName(className);
        clazz.getMethod(methodName).invoke(clazz);
    }
}

最新更新