How can I check if a method is static using reflection?

I want to discover at run-time ONLY the static Methods of a class, how can I do this? Or, how to differentiate between static and non-static methods.


Asked by: Paul654 | Posted: 28-01-2022






Answer 1

Use Modifier.isStatic(method.getModifiers()).

/**
 * Returns the public static methods of a class or interface,
 *   including those declared in super classes and interfaces.
 */
public static List<Method> getStaticMethods(Class<?> clazz) {
    List<Method> methods = new ArrayList<Method>();
    for (Method method : clazz.getMethods()) {
        if (Modifier.isStatic(method.getModifiers())) {
            methods.add(method);
        }
    }
    return Collections.unmodifiableList(methods);
}

Note: This method is actually dangerous from a security standpoint. Class.getMethods "bypass[es] SecurityManager checks depending on the immediate caller's class loader" (see section 6 of the Java secure coding guidelines).

Disclaimer: Not tested or even compiled.

Note Modifier should be used with care. Flags represented as ints are not type safe. A common mistake is to test a modifier flag on a type of reflection object that it does not apply to. It may be the case that a flag in the same position is set to denote some other information.

Answered by: Maddie247 | Posted: 01-03-2022



Answer 2

You can get the static methods like this:

for (Method m : MyClass.class.getMethods()) {
   if (Modifier.isStatic(m.getModifiers()))
      System.out.println("Static Method: " + m.getName());
}

Answered by: Julian103 | Posted: 01-03-2022



Answer 3

To flesh out the previous (correct) answer, here is a full code snippet which does what you want (exceptions ignored):

public Method[] getStatics(Class<?> c) {
    Method[] all = c.getDeclaredMethods()
    List<Method> back = new ArrayList<Method>();

    for (Method m : all) {
        if (Modifier.isStatic(m.getModifiers())) {
            back.add(m);
        }
    }

    return back.toArray(new Method[back.size()]);
}

Answered by: Sawyer358 | Posted: 01-03-2022



Similar questions

reflection - Does Java have an "is kind of class" test method

I have a baseclass, Statement, which several other classes inherit from, named IfStatement, WhereStatement, etc... What is the best way to perform a test in an if statement to determine which sort of Statement class an instance is derived from?


Java: Easy way to get method stub out of class files within a JAR file? Reflection?

I'm searching for a way to get a list of method stubs of all classes within a jar file. I'm not sure where to start... May I use Reflection or Javassist or some other tools of which I've not heard yet!? At least it may be possible to unpack the jar, decompile the class files and scan with a line parser for methods, but I think that is the most dirtiest way ;-) Any ideas? Kind Regards


java - How to get this Method object via reflection?

This is the class: public class Foo { public void bar(Integer[] b) { } } Now I'm trying to get this method via reflection: Class cls = Foo.class; Class[] types = { /* what is here */ }; cls.getMethod("bar", types); How to create this "type"?


java - How to know if method is taking array as param using reflection

I am trying to invoke the API with the given input parameters. Input params are coming as a List. Now my job is get the API's parameter types one by one and build the required type instance from List. I am able to do for simple java types , List, Set but I am stuck at the array. Method method = getMethodFromTheClassBasedOnvalues( loadedClass, apiName, numberOfParams); Type[] apiMethodParams = metho...


java - Getting method via reflection

My previous post was not very clear, sorry for that. I will try to give a better example of what I am trying to do. I have an Java application that will load .class files and runs them in a special enviroment (the Java app has built-in functions) Note: This is not a library. That Java application will then display an applet, and I want to modify the variables in the applet. The main class of the app...


Can a method figure out its own name using reflection in Java

This question already has answers here:


java - Using Reflection to call a method on a field

Okay been working on this too long and can't get it to work. I have a list of Thread types that can be different classes i.e. WriteFileData(extends Thread). I want to for loop through that list and do a call to add to queue a byte array. I currently have this in a Broker class // consumers is filled with different Thread types all having a queue // variable of type LinkedBlockingQueue ArrayList&lt;Thread...


reflection - How do I know if a class has a method in java and how do I invoke it

I need to know if a java class has the method public double getValue() if there is a method. I need call the method. Sorry, I forgot to say that this need to do at runtime


How to call a void method in java using reflection

If I call a method using reflection, the only way I can get it to work properly without throwing a null pointer exception is by returning an int value in the method I'm calling. For example, the method I want to call: public int setScore(int n) { this.score = n; return 1; } The way I call it: Method setScore = myClass.getMethod("setScore", new Class&lt;?&gt;[]{int.c...


reflection - Run a method before and after a called method in Java

I'm trying to write a Java program such that after calling a methodA(), first a method named methodBeforeA() is called and then methodA() gets executed followed by another method being called named, methodAfterA(). This is very similar to what Junit does using Annotations (using the @Before, @Test, @After), so i think it should be possible using reflection but i don't have a very good cl...


reflection - Reflecting method's actions in Java

I'd like to know how to - if even possible - reflect what method calls are executed inside the method during execution. I'm especially interested in either external method calls (that is, methods in other classes) or calling some specific method like getDatabaseConnection(). My intention would be to monitor predefined objects' actions inside methods and execute additional code if some specific conditions are met li...


Is there a general "back-end" library for Java reflection

I'm currently working with a specialized, interpreted, programming language implemented in Java. As a very small part of the language, I'd like to add the ability to make calls into Java. Before I dive into all of the nitty-gritty of reflection, I was wondering if anyone knew of a general library for doing the &quot;back-end&quot; part of invoking Java code reflectively. That is, I parse a string (I define the gram...


reflection - Validate reflected method return type and parms in Java

I have a generic Callback object which provides a (primitive) callback capability for Java, in the absence of closures. The Callback object contains a Method, and returns the parameter and return types for the method via a couple of accessor methods that just delegate to the equivalent methods in Method. I am trying to validate that a Callback I have been supplied points to a valid method. I need the return type ...


Can I discover a Java class' declared inner classes using reflection?

In Java, is there any way to use the JDK libraries to discover the private classes implemented within another class? Or do I need so use something like asm?


reflection - How do I intercept a method invocation with standard java features (no AspectJ etc)?

I want to intercept all method invocations to some class MyClass to be able to react on some setter-invocations. I tried to use dynamic proxies, but as far as I know, this only works for classes implementing some interface. But MyClass does not have such an interface. Is there any other way, besides implementing a wrapper class, that delegates all invocations to a member, which is an instance of the MyClass...


java - Calling a method using reflection

Is it possible to call a method by reflection from a class? class MyObject { ... //some methods public void fce() { //call another method of this object via reflection? } } Thank you.


java - How do reflection and remoting work internally?

I am curious to know how Reflection and Remoting in .net work internally. I also hear that .net can use remoting to communicate with applications written in other languages (such as Java). How does that work? This is probably a large question so an answer that briefly touches upon each question is reasonable.


reflection - Dumping a java object's properties

Is there a library that will recursively dump/print an objects properties? I'm looking for something similar to the console.dir() function in Firebug. I'm aware of the commons-lang ReflectionToStringBuilde...


c# - How does "static reflection" work in java? (ex. in mockito or easymock)

I'm a .NET guy - and I mainly code in C#. Since C# 3.0, we can leverage lambda expressions and expression trees to use static reflection. For example, it is possible to implement GetMethodName in the following snippet to return the name of the method passed ...


Is Java Reflection on Inherited Methods Different in Windows and Linux?

While setting up Hudson for continous integration testing (on a JeOS server), I've come across some strange behaviour I'm hoping the fine people at SO can explain to me. Our unit tests depend heavily on the use of domain objects, with lots of properties that must be set (due to null constraints in the database). In order to keep our tests readable, we have created a class InstantiationUtils that can instantiate an ...






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top