Thursday 16 August 2012

NTSystem VS System.getProperty("user.name")

Yesterday i was reviewing my friends code, In that i found a class called NTSystem my friend was actually using this class because of this method
public String getName(); //This method gets you the current logged in user
I asked him do you think this application will work in Linux and he replied yes of course then i smiled and said try it out he tried and call me this morning and said the application is throwing
ClassNotFoundException 

why so ?


Thing is that Beginners don't understand the working, they just somehow learn (in chalega ..chalega style) or copy the code from internet the things to know is, though Java is machine independent JVM is not .
JVM is exclusive made for each OS. 

Thats why when you use NTSystem class in windows it works like a charm but the code throws an Exception when you run it on some other OS just because the JVM don't know what NTSystem is !

If you had download the JDK for Linux, there you will not find the NTSystem class.

So the bottom line is if you want to get the current logged in user in Java always use 
System.getProperty("user.name");
This Method has 2 benefits

  1. Your code will be machine independent
  2. You will get the current logged in user 



2 comments:

  1. Yes NTSystem only works on windows, but I do not recommend using System.getProperty("user.name") blindly either..

    Its a system property and as such one can trick the JVM by passing in any value they want.

    Its also deceiving to say that it will get the current logged in user. System.getProperty("user.name") will return the user that launched the process, which is not necessarily the user that is currently logged in.

    So really it depends what you are trying to do.. I would say in most cases fetching the system property makes the most sense, but there are also situations where you should flat out not be using it either.

    ReplyDelete
    Replies
    1. perfectly said, what you are talking about is multi-user OS where more than 1 user can logged in at any given instant of time.

      Delete