10

I know you can retrieve the username with something like System.getProperty("user.name") but I am looking for a way to retrieve the first and last name of the current user.

Is there a native Java library that does this? Or do you have to plug into the Windows API? Or maybe you have to pull it from Active Directory? This seems relatively easy with .NET but I can't find a way to do it in Java.

Community
  • 1
  • 1
aus
  • 1,394
  • 1
  • 14
  • 19
  • I don't have the answer but you might look at [JNA](https://github.com/twall/jna) and see if that would help. – Brian Roach Feb 10 '12 at 17:45
  • How do you do it with .NET? If it's a system call, it can be done in Java with JNA. – Mark Peters Feb 10 '12 at 17:45
  • Added a link to how to do it in .NET. Considering just tapping into ActiveDirectory, but I thought for sure there it would be simpler. – aus Feb 10 '12 at 19:23

2 Answers2

9

As Brian Roach suggested in the comments, it's pretty straight-forward to do this with JNA, since it has a built-in wrapper for Secur32 which wraps the GetUsernameEx() function (which is ultimately the system call wrapped by the .NET library you linked to above).

Use would be something like this:

import com.sun.jna.ptr.IntByReference;
import com.sun.jna.platform.win32.Secur32;

// ...    

char[] name = new char[100];  // or whatever is appropriate
Secur32.INSTANCE.GetUserNameEx(
     Secur32.EXTENDED_NAME_FORMAT.NameDisplay,
     name,
     new IntByReference(name.length)
);

String fullName = new String(name).trim();

Note that this will give you the full name in the same format as you'd get typing net user %USERNAME% /domain at the command prompt.

ig0774
  • 39,669
  • 3
  • 55
  • 57
5

Or just,

String fullName = Secur32Util.getUserNameEx(Secur32.EXTENDED_NAME_FORMAT.NameDisplay);

But it is the same, as the upper answer

serg
  • 1,003
  • 3
  • 16
  • 26