简体   繁体   中英

How can I use instanceof Keyword Java

Is this the right way of validating using the instanceof keyword in java? Can I not use the || operator with this keyword? I am seeing errors in the line where I am writing the if condition to check if FieldName < = 0 and also when I am checking if it is equal to null or empty. Can anyone help me with the right way of writing the following piece of code. Thank you.

public static boolean validation(Object FieldName, String Name) {
       if(FieldName instanceof Integer) {
         if ((int) FieldName < = 0) {

         errorCode = "EXCEPTION";
         errorMsg = "Required field " + Name + " was not provided";
         logger.debug(Name+ " is null ");
           return true;
 }
   else {
} 
}
   else if (FieldName instanceof String) {
      if(FieldName == null || FieldName.equals("")) {
        errorCode = "EXCEPTION";
        errorMsg = "Required field " +Name+" was not provided";
        logger.debug(Name+" is null ");
          return true;

 }
  //Here I check the fields for null or empty 
}

Why not have two methods, one which takes an Integer and validates that, and one that validates Strings? Would that be simpler?

The line needs to be changed to

if (((int) FieldName) <= 0) {

when you don't put the parentheses around the cast completely the compiler will still believe it is an object and not an integer.

Try this. change the if and else body according to you

public static boolean validation(Object FieldName, String Name) {
  if (FieldName instanceof Integer) {
    if (((Integer)FieldName) <= 0) {

    //an integer <= 0

      return true;
   } else {
    // an integer >= 0
      return true;
  }
 } else if (FieldName instanceof String) {
   if (FieldName == null || FieldName.equals("")) {

   // a String empty or null

     return true;

   }
  else {
     // a String non empty
     return true;
   }

 }
 return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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