vendredi 14 février 2020

How do I properly test the char[ ] fields in my custom object for nulls, blanks, or empty? and Why do char[ ] indicate a length of 11?

I am researching how to use reflection to initialize a custom object. As an example, my object has several fields of differing types, however NONE of the fields are of the String type. I used chararrays instead of strings because I want to clear the objects out and not worry about immutable Strings being around in the heap should the applictation crash.

In addition, because the class implements CharSequence, the static fields buff, offset, and count are required. Also worth mentioning, the getters and setters are synchronized since this object will be used in a multi-threaded environment. Finally, there is a custom list of Person objects called People which lives in its own People.java file and is a customized collection of Person objects. Additional details about the object are elided for brevity.

The question is, how do I test for empty, blank, or null fields in my Person object? In my main class, I want to test for null, empty, or blank before inserting said object into a backend database. I have tried creating both a Person.isNull() and a similar Person.hasNull() function to test for empty values in the char[] fields, but the results are ABSOLUTELY NOT what I expected. The println statemnt inside the test for isCharArray revealed some THINGS I CURRENTLY DO NOT UNDERSTAND.....

Here is some sample output:

Size of byte: 1 bytes.
Size of short: 2 bytes.
Size of int: 4 bytes.
Size of long: 8 bytes.
Size of char: 2 bytes.
Size of float: 4 bytes.
Size of double: 8 bytes.
buff: char[] 11
personID: char[] 11
personTitle: char[] 11
personFirstName: char[] 11
personLastName: char[] 11

which was created using the following System.out.println statement:

System.out.println(f.getName() + ": " + f.getType().getCanonicalName() + " " +  String.valueOf(value).length());

and raises 2 questions:

  1. Why 11?!!!!!
  2. How do I properly test for blank, empty, or zero-length fields?!!!

Please help....

public class Person  implements Serializable, 
                                Comparable<Person>,  
                                CharSequence, 
                                Cloneable   { // the object to model

    //  Fields 0, 1, and 2 are required to implement CharSequence                                   
    //  http://www.java2s.com/Tutorial/Java/0040__Data-Type/implementsCharSequence.htm
    private  static char[] buff = {'\0'};   // No static fields are ever                    // Field 0
    private  static int offset  = 0;        // written to file. Their values                // Field 1
    private  static int count   = 0;        // must be reconstructed.                       // Field 2  

    // default serialVersion id
    private static final long serialVersionUID = 7891011129876814235L;                      // Field 3
    private final static LocalDateTime rightNow = LocalDateTime.now();  

    private long   localSerialVersionUID= serialVersionUID;  //1st field written to file    // Field 4  
    private LocalDateTime personCreatedDateTime= rightNow;                                  // Field 5 
    private LocalDateTime  personLastUpdate    =  rightNow; // (YYYY-MM-DD)                 // Field 6  
    private char[] personID              = {'\0'}; // (PK)  possibly int auto increment     // Field 7 
    private char[] personTitle           = {'\0'};                                          // Field 8 
    private char[] personFirstName       = {'\0'};                                          // Field 9 
    private char[] personLastName        = {'\0'};                                          // Field 10 
    private LocalDate   personDOB        =  LocalDate.parse("1010-10-10"); // (YYYY-MM-DD)  // Field 11



    public Person( 
            final long serialUID,                           //4        
            final LocalDateTime createdDateTime,            //5 
            final LocalDateTime lastUpdate,                 //6
            final char[] id,                                //7 
            final char[] title,                             //8 
            final char[] firstName,                         //9 
            final char[] lastName,                          //10 
            final LocalDate   DOB                           //11                                                   
    ) {                                                
        this.localSerialVersionUID(serialUID);           //4 
        this.personCreatedDateTime(LocalDateTime.now()); //5 
        this.personLastUpdate(lastUpdate);               //6
        this.personID(id);                               //7 
        this.personTitle(title);                         //8 
        this.personFirstName(firstName);                 //9 
        this.personLastName(lastName);                   //10
        this.personDOB(DOB);                             //11
    }   

    public boolean hasNull() {
        Field fields[] = this.getClass().getDeclaredFields();

        for (Field f : fields) {
            f.setAccessible(true);

            try{
                    Object value = f.get(this);
                    if ( value == null) {return true; } // default condition

                    boolean isCharArray =  f.getType().getCanonicalName().equals("char[]" );


                    // No need to check fields that are not char[]
                    if (( isCharArray) ) {      

    // ************* this compiles and executes (doesn't crash), but it doesn't produce intended results *********

                        System.out.println(f.getName() + ": " + f.getType().getCanonicalName() + " " +  String.valueOf(value).length());

                        if ( String.valueOf(value).length() == 0)  {return true;}
                        if ( String.valueOf(value).isEmpty())      {return true;}
                        if ( String.valueOf(value).isBlank())      {return true;}
                        if ( String.valueOf(value).equals('\0'))   {return true;}

                    }   

    // ************* this compiles and executes (doesn't crash), but it doesn't produce intended results *********


                } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return false;
        }
    }         


    //enter code here


    /**
     * @param args
     */
    public static void main(String[] args)  {
        People<Person> people = new People()<>; //customized list of person objects
        People<Person> people2 = new People()<>; //customized list of person objects

        Person thomas = new Person().personFirstName("Thomas".toCharArray()); 
                // all other char array fields = {'\0'}
        people.add(thomas);

        Person sybil =  new Person().personFirstName("Sybil".toCharArray()); 
                // all other char array fields = {'\0'}
        people2.add(sybil);

        if (!thomas.hasNull() ){    // ******* currently this test fails and a Person gets inserted to the People list
            People.insertPerson(thomas);
        }
        if (!sybil.hasNull() ){     // ******* currently this test fails and a Person gets inserted to the People list
            People.insertPerson(sybil);
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire