Reputation: 53
i have 2 java applications connected to each other via LAN (wifi network)
the first one ServerApp.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);
}
}
}
the second one ClientApp.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 server\n");
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);
}
}
}
what happens is, the client app send a message to the server app via LAN using the server IP address - the server app have a method call zzz() so all I want is how do I make the client app call this method ( if possible )
thanks
Upvotes: 0
Views: 520
Reputation: 887
@MichalLonski how to I make the "obj" indicate to the ServerApp
As it is static
method you have to point ServerApp.class
, like below:
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);
}
}
You can change it to use not static, but instance methods. In order to do that you have to create an instance of ServerApp class, like this:
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);
}
}
Edit:
If you want to specify also the class of which method you want to call, you can do it this way:
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);
}
}
Upvotes: 1