Tuesday, 15 April 2014

Java - How to restrict method calling from a specific method -


I have an awkward requirement where I need to make sure that only one special method can be made public - Stable) Law inheritance can not be used from one other class.

An alternative to using StackTrace is as follows:

ClassA.java

  package org .rnd.stack; Public class class A {Public Zero Law A () entered illegal manner illegally {Exception = False = New exception ("Fake-Ignor"); StackTrace Element [] Stack = Fake .getStackTrace (); StackTrace element st = stack [1]; If ("org.rnd.stack.ClassB" .equals (st.getClassName ()) & amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; methodbar; Is not allowed ");}}}  

ClassB.java

  package org.rnd.stack; public class ClassB {Public Null Method B (illegal) throws illegal IllegalAccessException {New class (). MethodA ();} Public illegal illegal method throws (IllegalAccessException {New class (.). MethodA ();} Public static zero main (string [] Args) {try {new classb (). MethodB ();} hold (IllegalAccessException e) {// TODO auto generated Holding block e.printStackTrace ();}}}  

The above solution works fine, but due to quality control in code audit, I will come up with some other (or rather) better solution Is there a better way to achieve this?

The way is that you need to make an exception to get stacktrace, you can use thread methods Areas are.

  StackTraceElement [] stack = Thread.currentThread (). GetStackTrace ();  

In addition to this you want to use the class instead of writing the class. For example:

  if (ClassB.class.getName (.) Equals (st.getClassName ()) and "methodB" .equals (st.getMethodName ()) {system .out.println ("You have permission to call"); } Other {Removing new illegal conclusions ("You are not allowed to call"); }  

Apart from this, I do not know how you can do better without changing your argument or using heritage.


No comments:

Post a Comment