getClass() on null objects

Does anyone know of a way to get the Class from a null object?

Here's an example of what I'm looking for:

public class Main {
      public static void main(String[] args) {
            getClassFromObjectInstance((String)null);
      }
      
      private static Class getClassFromObjectInstance(Object arg) {
            // Get the class and return it
            return arg.getClass();
      }
}

The problem with the above code is:

Exception in thread "main" java.lang.NullPointerException
      at Main.getClassFromObjectInstance(Main.java:9)
      at Main.main(Main.java:4)

Any ideas?

-M
LVL 1
mikedehaanAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

StillUnAwareCommented:
There is no way to get the class from null. Null efectively is a special variable representing nothing, You can't get any info from nothing.
Tommy BraasCommented:
How could you possibly get a class from a null value? Null represents nothing, void.

Furthermore, what is the purpose of your code? You can get the class from any object instance in Java by calling getClass(), such as you're already doing in your code.
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

Tommy BraasCommented:
>> rama_krishna580
Maybe you should read the question properly before offering your answer/solution...
mikedehaanAuthor Commented:
I guess what I'm really looking for is the result of a type-cast.  I know you can't get anything from a null value, but somehow (hopefully during runtime), a decision is made. for example:

      private static void func1(Object arg) {
            System.out.println("func1(Object arg)");
      }
      
      private static void func1(String arg) {
            System.out.println("func1(String arg)");
      }
      
      private static void func1(Integer arg) {
            System.out.println("func1(Integer arg)");
      }

In order to call these functions, a null value must be cast:

func1((String)null); // This null is a null String
func1((Integer)null); // This null is a null Integer

In truth, I don't think what I'm looking for is possible.  Apache seems to have realized the need for this logic given the method described in the previous post.  Unfortunately, the function requests a value to return for when the object is null.  I have nothing to pass in as that parameter.  That's the value I'm looking for.

Java's reflection API also requires the classes to be explicitly named.  Example, the getMethod() function:
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#getMethod(java.lang.String, java.lang.Class[])

To narrow the focus a little more, what I'm looking for specifically is a way to get the most appropriate constructor from MyClass.class.getConstructors() when all I have is as Object[] of parameters (instances - not Class[])

-M
Tommy BraasCommented:
I am not familiar enough with the JRE, but I know that when you cast a null it is only to satisfy the compiler, i.e. the method binding is done at compile time, not runtime.

>> To narrow the focus a little more, what I'm looking for specifically is a way to get the most appropriate
>> constructor from MyClass.class.getConstructors() when all I have is as Object[] of parameters (instances - not
>> Class[])

I would suggest that you either have a default constructor that you call for null values, and handle the rest of the cases appropriately. Like has been highlighted before, a null is a null and has no type.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mayank SAssociate Director - Product EngineeringCommented:
>> In order to call these functions, a null value must be cast:

No, a null value need not be cast because even that will result in a null. Why don't you try passing a few non-null arguments and you'll realize what it prints:

>> getClassFromObjectInstance((String)null);

System.out.println ( getClassFromObjectInstance ( "String object" ) ) ;
System.out.println ( getClassFromObjectInstance ( new Object () ) ) ;



WebstormCommented:
Hi mikedehaan,

If you're trying to get class without creating instance of that class, use class attribute instead of getClass() method :

       Class cl_s=String.class;
       Class cl_i=Integer.class;
mikedehaanAuthor Commented:
>>> No, a null value need not be cast because even that will result in a null. Why don't you try passing a few non-null
>>> arguments and you'll realize what it prints:

Not true.  Try calling these functions without the cast on the null literal and the compiler will complain.

Alas, orangehead911 is correct.  The casting done on a null is simply done to satisfy the compiler and not available during runtime.

Thank you all for your help.
Mayank SAssociate Director - Product EngineeringCommented:
Since you have:

>> private static Class getClassFromObjectInstance(Object arg) {

I see no reason why a null cannot be passed to it and why you need to pass a String.
Mayank SAssociate Director - Product EngineeringCommented:
Why do you think this would not compile:

public class Main {
     public static void main(String[] args) {
          System.out.println ( getClassFromObjectInstance ( null ) ) ;
     }

     private static Class getClassFromObjectInstance(Object arg) {
          // Get the class and return it
          return arg.getClass();
     }
}

Or this:

public class Main {
     public static void main(String[] args) {
          System.out.println ( getClassFromObjectInstance ( new Object () ) ) ;
     }

     private static Class getClassFromObjectInstance(Object arg) {
          // Get the class and return it
          return arg.getClass();
     }
}

Or:

public class Main {
     public static void main(String[] args) {
          System.out.println ( getClassFromObjectInstance ( "abc" ) ) ;
     }

     private static Class getClassFromObjectInstance(Object arg) {
          // Get the class and return it
          return arg.getClass();
     }
}

All of them would compile. Since you are accepting an Object argument, there is no need to type cast to a String (in fact if the object is not a String, it will create a problem).
Mayank SAssociate Director - Product EngineeringCommented:
>> Not true.

Then you don't understand when we need to type-cast objects and when we should not do that.
Mayank SAssociate Director - Product EngineeringCommented:
Actually StillUnaware's first comment and orangehead's first comment were the correct and simply complete answers to this.
mikedehaanAuthor Commented:
My post above had three different functions called func1().  They each returned the same datatype (void) and had the same number of parameters, therefore overridding each other.

Since all three functions could technically accept a null parameter, the compiler gets confused and doesn't know which function to call.

func1(null);

/*
 Did you mean func1((String)null); func1((Integer)null); or func1((Object)null); ??
*/

I was hoping that the answer you give the compiler by type-casting would somehow be available during runtime.  Unfortunately, this is not the case.

-M
Mayank SAssociate Director - Product EngineeringCommented:
When you have polymorphism, in that case, passing null is not really what you would practically want to do because the polymorphed methods work based on the parameter passed. Now if the parameter itself is null, there is not much to do :) otherwise, you would practically pass non null values to them, like:

func1 ( new Object () ) ; // will call func1 (Object)
func1 ( "a" ) ; // will call func1 (String)
func12 ( new Integer ( 1 ) ) ; // will call func1 (Integer)

and in that case, a type-cast is not required because the JVM will know from the type of the object (perhaps internally through getClass ()) as to which exact method is to be invoked.
mikedehaanAuthor Commented:
You're not wrong.  This just doesn't help me with my original issue.

Another way to look at this is:

Object obj = (String)null;

How can I tell during runtime that obj really points to a String object.  

The answer is...it doesn't.  The variable obj doesn't point to anything (thank you StillUnAware).  Type-casts like this one are meant to satisfy the compiler and don't provide me with the information I need during runtime (thank you orangehead911).  I know, the above statement does not require the type-cast, but that's not my point.  I'm just trying to demonstrate my question.

-M
Mayank SAssociate Director - Product EngineeringCommented:
>> The answer is...it doesn't

Yes.

>> Type-casts like this one are meant to satisfy the compiler

Yes, but don't do them on nulls :) it is not of any practical use. Actually since the question was titled with getClass () and started with only one getClassFromObjectInstance () method (not multiple, polymorphed ones), it later went an entirely different way....
Tommy BraasCommented:
;-D
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.