Question

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

Était-ce utile?

La solution

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..

Autres conseils

You're getting that error because that code is not logical, the compiler knows that String string is an string, that's for sure, so it prevents you from trying to do instanceOf of an string, which is final and does not implements Cloneable

You can see more information about this here

If you try to check if a give string (for example: "java.lang.String") represents the valid name of a class in the class loader you could use Class.forName(className). Something like in this example:

public class Demo {
    public static void main(String[] args) {

        System.out.println(isInstance("java.lang.String")); // will print true
        System.out.println(isInstance("Longssss"));         // will print false 

    }
    public static boolean isInstance(String string) {
        try {
            return Class.forName(string).getName().equals("java.lang.String");
        } catch (Exception e) {
            return false;
        }
    }
}

You will have to explore the Class.forName method

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top