Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could do it the following way, however you should carefully consider if you really want to use this approach as it is very slow and quite frankly, bad practice. I'll put it up anyway as to how you <em>can</em> do it:</p> <pre><code>public final class Secured { private static final Set&lt;Class&lt;?&gt;&gt; allowedCallers = new HashSet&lt;&gt;(); static { allowedCallers.add(Allowed.class); } private static final class SecurityManagerExtension extends SecurityManager { private static final int OFFSET = 4; @Override protected Class&lt;?&gt;[] getClassContext() { return super.getClassContext(); } private Class&lt;?&gt; getCaller() { try { return getClassContext()[OFFSET]; } catch (ArrayIndexOutOfBoundsException e) { return null; } } } private Secured() { // protect against reflection attack Class&lt;?&gt; caller = new SecurityManagerExtension().getCaller(); if (!this.getClass().equals(caller)) { throw new IllegalStateException(); } System.out.println("Secured instance constructed!"); } public static Secured createInstance() { // this gets the class name of the calling class Class&lt;?&gt; caller = new SecurityManagerExtension().getCaller(); if (allowedCallers.contains(caller)) { System.out.println("Created instance by '" + caller + "'!"); return new Secured(); } else { System.out.println("No instance created because call was made by '" + caller + "'!"); return null; } } } </code></pre> <p>Note the final keyword on the class to prevent subclassing. If you need to subclass the class yourself, move the final keyword to the factory method. Also note that this is not protected against serialization attacks.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload