Skip to content

Commit

Permalink
protection against reflection
Browse files Browse the repository at this point in the history
  • Loading branch information
n9Mtq4 committed Oct 25, 2015
1 parent c2f1581 commit 33f26d6
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions src/main/java/com/n9mtq4/reflection/ReflectionProtector.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.n9mtq4.reflection;

/**
* A class that contains methods to protect your methods
* against the use of reflection.
*
* <p>
* Created by will on 10/24/15 at 7:39 PM.
*
* @since v1.1
* @author Will "n9Mtq4" Bresnahan
*/
@SuppressWarnings("unused")
public class ReflectionProtector {

/**
* Returns if the calling method was invoked with reflection.
* <p>
* WARNING: this method is (relatively) slow, so use it sparingly.
*
* @return If the calling method was invoked with reflection
* */
public static boolean usedReflection() {
return usedReflection(3, Thread.currentThread().getStackTrace());
}

/**
* Returns if the stacktrace at the given index is a reflection one.
* <p>
* WARNING: this method is (relatively) slow, so use it sparingly.
*
* @param index The index for the stacktrace
* @return if the stacktrace at the given index is a reflection one.
* */
public static boolean usedReflection(int index) {
return usedReflection(index, Thread.currentThread().getStackTrace());
}

private static boolean usedReflection(int index, StackTraceElement[] stackTraceElements) {
return usedReflection(index, index + 1, stackTraceElements);
}

/**
* Returns if the stacktrace within the two ranges is a reflection one.
* <p>
* WARNING: this method is (relatively) slow, so use it sparingly.
*
* @param min The starting stacktrace index
* @param max The ending stacktrace index
* @return if the stacktrace within the two ranges is a reflection one
* */
public static boolean usedReflection(int min, int max) {
return usedReflection(min, max, Thread.currentThread().getStackTrace());
}

private static boolean usedReflection(int min, int max, StackTraceElement[] stackTraceElements) {
for (int i = min; i < max; i++) {
if (stackTraceElements[i].getClassName().startsWith("java.lang.reflect") || stackTraceElements[i].getClassName().startsWith("sun.reflect")) return true;

}
return false;
}

}

0 comments on commit 33f26d6

Please sign in to comment.