4

Why I get this error

Exception in thread "main" java.lang.SecurityException: Unsafe

when I run my code

public class UnsafeString {
    public static void main(String[] args) throws InstantiationException {
        String obj = new UnsafeString().create();
        System.out.println(obj);
    }
    public String create() throws InstantiationException {
        return (String) sun.misc.Unsafe.getUnsafe().allocateInstance(String.class);
    }
}
barbara
  • 3,111
  • 6
  • 30
  • 58

1 Answers1

4

You can't use Unsafe directly. It involves some hacks to avoid the SecurityException (mainly getting the Unsafe instance via reflection). Assuming that you're not doing something stupid, like using it in production code, here's a way to retrieve it.

There's also a rumor that it would become a part of the public API later on.

Community
  • 1
  • 1
Kayaman
  • 72,141
  • 5
  • 83
  • 121