Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string is instance of a Class in Java [closed]

I would like to know how to check if a string is instance of a Class in a Server Side of ServerSocket programm. Α client gives an object of class Myclass1 and the server must check if a string that reads from client is instance of MyClass1 or another class(e.g. MyClass2, String, Integer, etc.)

That is my code:

  ObjectInputStream object_input = new ObjectInputStream(sock.getInputStream());
  String string = object_input.readLine();
  if (string instanceof MyClass1){...}
  else if(string instanceof MyClass2){...}

It makes an error and I don't know how to solve it. Please, help me

like image 589
user3403572 Avatar asked Apr 21 '26 04:04

user3403572


1 Answers

Rewrite your code as follows :

ObjectInputStream objectInput = new ObjectInputStream(sock.getInputStream());

        Object objectFromClient = objectInput.readObject();

        if (objectFromClient instanceof MyClass1) {

        } else if (objectFromClient instanceof MyClass2) {

        }// etc..
like image 132
Visruth Avatar answered Apr 23 '26 16:04

Visruth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!