Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

getClass() on null objects

Posted on 2006-04-18
18
Medium Priority
?
1,050 Views
Last Modified: 2008-03-10
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
0
Comment
Question by:mikedehaan
  • 7
  • 4
  • 4
  • +3
18 Comments
 
LVL 14

Assisted Solution

by:StillUnAware
StillUnAware earned 88 total points
ID: 16480365
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.
0
 
LVL 14

Expert Comment

by:Tommy Braas
ID: 16480557
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.
0
 
LVL 23

Assisted Solution

by:rama_krishna580
rama_krishna580 earned 80 total points
ID: 16480561
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 14

Expert Comment

by:Tommy Braas
ID: 16481898
>> rama_krishna580
Maybe you should read the question properly before offering your answer/solution...
0
 
LVL 1

Author Comment

by:mikedehaan
ID: 16482392
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
0
 
LVL 14

Accepted Solution

by:
Tommy Braas earned 332 total points
ID: 16483054
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.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16484825
>> 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 () ) ) ;



0
 
LVL 13

Expert Comment

by:Webstorm
ID: 16486345
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;
0
 
LVL 1

Author Comment

by:mikedehaan
ID: 16489244
>>> 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.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16489280
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.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16489296
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).
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16489304
>> Not true.

Then you don't understand when we need to type-cast objects and when we should not do that.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16489329
Actually StillUnaware's first comment and orangehead's first comment were the correct and simply complete answers to this.
0
 
LVL 1

Author Comment

by:mikedehaan
ID: 16489353
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
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16489387
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.
0
 
LVL 1

Author Comment

by:mikedehaan
ID: 16489489
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
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16489529
>> 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....
0
 
LVL 14

Expert Comment

by:Tommy Braas
ID: 16490625
;-D
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month20 days, 23 hours left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question