Code0
Code0

Reputation: 29

How Do I Use A Class As A Parameter In A Static Method

I'm aware that in static methods you can't use the keyword "this".

Now, I also know that if I want to call a method from that class that I'm currently in, I can use the class name,

Example: Main.someStaticMethod();

Now, if I want to use that class (the same as in the example above) in a parameter, how would I do that?

Main.someStaticMethodWithParam(Main);

That Doesn't work since the IDE thinks main is a parameter and thus just comes up with the error: Undefined variable.

Upvotes: 1

Views: 49

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

You should pass an instance of the class to your static method:

public class Main {
    private int x;
    public static <T> void printClassName(Class<T> clazz) {
        System.out.println(clazz.getName());
    }
    public static void main() {
        printClassName(Main.class);
    }
}

Prints (assuming the class is not inside a package):

Main

Upvotes: 1

Related Questions