How to Know If All the Variables in a Class Are Null

What is the best way to know if all the variables in a Class are null?

Try something like this:

public boolean checkNull() throws IllegalAccessException {
for (Field f : getClass().getDeclaredFields())
if (f.get(this) != null)
return false;
return true;
}

Although it would probably be better to check each variable if at all feasible.

Check if all the properties of class are null

You could make a property IsInitialized, that does this internally:

public bool IsInitialized
{
get
{
return this.CellPhone == null && this.Email == null && ...;
}
}

Then just check the property IsInitialized:

if (myUser == null || myUser.IsInitialized)
{ ... }

Another option is the use of reflection to walk over and check all properties, but it seems overkill to me. Also, this gives you the freedom to deviate from the original design (when you choose all properties, except one should be null for example).

How to check all properties of an class whether null or empty?

Something like this (checking for null, note, that non-string property can be empty):

// You don't need generic, Object is quite enough 
public static bool Check(Object instance) {
// Or false, or throw an exception
if (Object.ReferenceEquals(null, instance))
return true;

//TODO: elaborate - do you need public as well as non public properties? Static ones?
var properties = instance.GetType().GetProperties(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic);

foreach (var prop in properties) {
if (!prop.CanRead) // <- exotic write-only properties
continue;
else if (prop.PropertyType.IsValueType) // value type can't be null
continue;

Object value = prop.GetValue(prop.GetGetMethod().IsStatic ? null : instance);

if (Object.ReferenceEquals(null, value))
return false;

//TODO: if you don't need check STRING properties for being empty, comment out this fragment
String str = value as String;

if (null != str)
if (str.Equals(""))
return false;
}

return true;
}

Edit: the updated example provided shows, that you want to check fields as well as properties, not properties alone; in that case:

// You don't need generic, Object is quite enough 
public static bool Check(Object instance) {
// Or false, or throw an exception
if (Object.ReferenceEquals(null, instance))
return true;

//TODO: elaborate - do you need public as well as non public field/properties? Static ones?
BindingFlags binding =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;

// Fields are easier to check, let them be first
var fields = instance.GetType().GetFields(binding);

foreach (var field in fields) {
if (field.FieldType.IsValueType) // value type can't be null
continue;

Object value = field.GetValue(field.IsStatic ? null : instance);

if (Object.ReferenceEquals(null, value))
return false;

//TODO: if you don't need check STRING fields for being empty, comment out this fragment
String str = value as String;

if (null != str)
if (str.Equals(""))
return false;

// Extra condition: if field is of "WS_IN_" type, test deep:
if (field.FieldType.Name.StartsWith("WS_IN_", StringComparison.OrdinalIgnoreCase))
if (!Check(value))
return false;
}

// No null fields are found, let's see the properties
var properties = instance.GetType().GetProperties(binding);

foreach (var prop in properties) {
if (!prop.CanRead) // <- exotic write-only properties
continue;
else if (prop.PropertyType.IsValueType) // value type can't be null
continue;

Object value = prop.GetValue(prop.GetGetMethod().IsStatic ? null : instance);

if (Object.ReferenceEquals(null, value))
return false;

//TODO: if you don't need check STRING properties for being empty, comment out this fragment
String str = value as String;

if (null != str)
if (str.Equals(""))
return false;
}

return true;
}

how to check if the variable is null?

you can use .equals("") or .isEmpty()

check check if the variable is null

how to check if all the variable not empty in PHP

Like this:

$array = [
'first_name' => 'John',
'last_name' => 'Doe',
'email' => '',
];

if(count($array) != count(array_filter($array))){
echo 'some rows are empty';
}

If you want to know which specific fields are empty you can use array_diff_key

$array = [
'first_name' => 'John',
'last_name' => 'Doe',
'email' => '',
];

$filled = array_filter($array);

if(count($array) != count($filled)){
$empty = array_diff_key($array, $filled);
echo 'field(s) '.implode(', ', array_keys($empty)).' are empty';
}

Ouputs:

field(s) email are empty

Obviously you can improve on the error string, or what have you. So in your case I would do something like this

if(count($array) != count($filled)){
$empty = array_keys(array_diff_key($array, $filled));
$last = '';
if(count($empty) > 1 ){
$last = ' and '.array_pop($empty);
}
$fields = implode(', ', $empty).$last;
echo json_encode(array('condition' => 'error','data' => 'Please fill in '.$fields));
}

So it should output something like this:

Please fill in email

Please fill in first_name and email

Please fill in first_name, last_name and email

You could even do:

$empty = array_map(function($item){
return ucwords(str_replace('_', ' ', $item));
}, $empty);

Which would take, first_name and change it to First Name if you want to get fancy.

So... Putting all that togather:

$array = [
'first_name' => '',
'last_name' => '',
'email' => '',
];

$filled = array_filter($array);

if(count($array) != count($filled)){
$empty = array_map(function($item){
return ucwords(str_replace('_', ' ', $item));
},array_keys(array_diff_key($array, $filled)));
$last = '';
if(count($empty) > 1 ){
$last = " and '".array_pop($empty)."'";
}
$fields = "'".implode("', '", $empty)."'".$last;
echo json_encode(['condition' => 'error','data' => 'Please fill in '.$fields]);
}

Outputs:

{"condition":"error","data":"Please fill in 'First Name', 'Last Name' and 'Email'"}

You can see it here live

And now it tells them exactly what fields they need, instead of some generic error.

How to check all properties of an object whether null or empty?

You can do it using Reflection

bool IsAnyNullOrEmpty(object myObject)
{
foreach(PropertyInfo pi in myObject.GetType().GetProperties())
{
if(pi.PropertyType == typeof(string))
{
string value = (string)pi.GetValue(myObject);
if(string.IsNullOrEmpty(value))
{
return true;
}
}
}
return false;
}

Matthew Watson suggested an alternative using LINQ:

return myObject.GetType().GetProperties()
.Where(pi => pi.PropertyType == typeof(string))
.Select(pi => (string)pi.GetValue(myObject))
.Any(value => string.IsNullOrEmpty(value));

Check which combinations of parameters are null in Java

Write these utility functions and you can compare n terms easily.

public static boolean areAllNull(Object... objects) {
return Stream.of(objects).allMatch(Objects::isNull);
}

public static boolean areAllNotNull(Object... objects) {
return Stream.of(objects).allMatch(Objects::nonNull);
}

you can use these functions for n comparisons.

if(areAllNotNull(a) && areAllNull(b,c)) { 
//doSomething
}
else if(areAllNotNull(b) && areAllNull(a,c)) {
//doSomething
}
else if(areAllNotNull(c) && areAllNull(b,a)) {
//doSomething
}


Related Topics



Leave a reply



Submit