Java reflection super method

How to Call a Superclass Method Using Java Reflection

The difference is using getDeclaredMethod() , which gets methods of all visibilities ( public , protected , package/default and private ) instead of getMethod() , which only gets methods with public visibility.

Java Inheritance — calling superclass method

Note, that super is a reference to the parent class, but super() is its constructor.

Invoke Superclass method via reflection

As others have mentioned, it is not possible to call a superclass’s method through reflection if it has been overridden. If at all possible you should look for another way of solving your issue before doing this, such as yole’s suggestion, as this is both difficult to read and maintain (it could easily break unexpectedly if, for example, the setIcon() method implementation changes or the default_icon field changes name).

However, if you absolutely want to and must you can do something like this to «mimic» the method call based on the source for setIcon() here on line 1710.

public static void setButtonIcon(MyToggleButton button, Icon icon) if (button.getIcon() == icon) 
return;

Icon old = button.getIcon();

// Use reflection to set the icon field
try Field f = AbstractButton.class.getDeclaredField("default_icon");
f.setAccessible(true);
f.set(button, icon);
> catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) e.printStackTrace();
return;
>

button.firePropertyChange(AbstractButton.ICON_CHANGED_PROPERTY, old, icon);
button.revalidate();
button.repaint();
>

Java Reflection : invoking inherited methods from child class

You need to use getMethod(String name, Class. parameterTypes) instead of getDeclaredMethod

Can I use Reflection to call a method’s super method?

After trying several things, I’ve concluded that this just isn’t possible. (This doesn’t surprise me, but I thought I’d give it a shot. I’m often surprised by what you can do through reflection, but you can’t do this.)

Calling a method of subclass through reflection

You are invoking an instance method on a null instance — so it makes sense that you receive a NPE. Try this instead (passing an instance to the invoke method instead of null ):

a.getClass().getMethod("Run").invoke(a);

Note: the first call worked because you can call a static method on a null instance without causing a NPE.

Reflection: how to call superclass constructor which is hidden?

After some research I’m able to answer the question by myself.

Short answer: I can’t do this because if the superclass constructor is protected and hidden, the compiler is going to complain even if I found a way how to call the constructor via reflection.

Long answer: it turns out it’s not so complicated to «unhide» this stuff. Following this tutorial I’m able to extend the class to my needs.

See? A lot of noise for nothing, this is the answer I was looking for.

Читайте также:  Html css templates admin panel

Источник

Using Reflection to call super class method

send pies

posted 16 years ago

  • Report post to moderator
  • Assume that a Super class ‘A’ has, say, 20 methods. All of these are overriden in sub class ‘B’. Now in a method in sub class ‘B’ i want to call one of the super class methods based on a parameter to this method. i don’t want to put 20 if conditions to do this. Is there a way by which i can invoke the super class method using reflection. Note that this invocation should not call the overridern method in the sub class. Quite simply, is there a way to do «super.abcd()» using reflection.
    If not, just out of curiosity, can i do this using JNI.

    jQuery

    send pies

    posted 16 years ago

  • Report post to moderator
  • send pies

    posted 16 years ago

  • Report post to moderator
  • Hey thanks for answering prabhu. But my problem is that the methods are overriden in the sub class and i want to invoke the super class method. consider this example
    Class Base public void test() System.out.println(«test of base»);
    >
    >

    class Child extends Base public void test() < //overriding super class method
    super.test();// >
    >
    How do i replace line (1) using reflection, so that «test of base» is printed? (without creating a new instance of Base, ie., should be invoked on current instance)

    Marshal

    send pies

    posted 16 years ago

  • Report post to moderator
  • I don’t know if you can do it using reflection or JNI. But you can do it using the one line of code that you displayed with no trouble. And with zero if-conditions, not 20. (If you need to decide whether to call the super method or not, you have to execute the if’s anyway.) So I would do that.

    send pies

    posted 16 years ago

  • Report post to moderator
  • Hey paul,
    I was just trying to give an example. In the actual scenario, I have many super class methods, all of which are overriden,(either in this class or in one of the sub classes). and i need to invoke one of the super class methods based on a input parameter to the method «test». consider this:

    class Child extends Base public void test(String methodToCall) <
    if(«test1».equals(methodToCall) super.test1();
    >
    else if(«test2».equals(methodToCall)) super.test2();
    >
    ..
    ..
    ..
    else if(«test100».equals(methodToCall)) super.test100();
    >
    >
    >

    It would be a lot more easier if i can replace this redundant code with reflection.

    Источник

    Invoke Super class methods using Reflection

    Question: I have 2 classes, say A & B: Now, I am using reflection to invoke the methods on Class A. I would also like to invoke the printHelloWorld method present in Class B. I tried using Also tried as But none of them work; they throw an instantiationexception. That’s the evaluate method from IntegerIntegerAddition Class and I have also the IntegerDoubleAddition Class evaluate method So the variable name could have «IntegerIntegerAddition» or «IntegerDoubleAddition» and I want with both of them call to the Evaluate method with the 2 parameters.

    Invoke Super class methods using Reflection

    I have 2 classes, say A & B:

    Class A extends B < public void subClassMthd()< System.out.println("Hello"); >> Class B < public void printHelloWorld < System.out.println("Hello"); >> 

    Now, I am using reflection to invoke the methods on Class A. I would also like to invoke the printHelloWorld method present in Class B.

    Class clazz = Class.forName("com.test.ClassA"); Object classAInstance= clazz.newInstance(); Method superClassmthd = classAInstance.getClass() .getSuperclass().getMethod("printHelloWorld", null); superClassmthd.invoke(classAInstance); 
    Class clazz = Class.forName("com.test.ClassA"); Object classAInstance= clazz.newInstance(); Class superClazz = Class.forName(classAInstance.getClass().getSuperclass().getName()); Object superclassInstance = superClazz.newInstance(); Method superClassmthd = superclassInstance.getMethod("printHelloWorld", null); superClassmthd.invoke(superclassInstance ); 

    But none of them work; they throw an instantiationexception.

    Читайте также:  Many-to-Many Relationship

    What am I doing wrong here?

    Method mthd = classAInstance.getClass().getSuperclass().getDeclaredMethod("XYZ"); mthd.invoke(classAInstance) 

    The difference is using getDeclaredMethod() , which gets methods of all visibilities ( public , protected , package/default and private ) instead of getMethod() , which only gets methods with public visibility.

    What is the visibility of the methods you want to call (public, private etc). If you want to see methods which you cannot call directly, you should use getdeclaredmethod().

    Also, what the the constructors of your classes like? InstantiationException indicates that you are having trouble getting an instance of class A (or B).

    I have the following code and it works:

    import java.lang.reflect.Method; public class A extends B < public static void main(String[] args) throws Exception < A classAInstance = new A(); Method mthd = classAInstance.getClass().getSuperclass().getMethod("XYZ", null); mthd.invoke(classAInstance); >> 

    Java Trying to do reflection(class instance and invoke, You could do something like this: Method evaluate = instance.getClass ().getDeclaredMethod ( «evaluate», int.class, int.class ); evaluate.invoke ( instance, 3, 1 ); This should find the exact method by parameter type ( alternatively use «int.class, long.class» for your second method ) & invoke it, here using example …

    Java Trying to do reflection(class instance and invoke method at runtime)

    String name = "expevaluator." + super.left.getClass().getSimpleName() + super.right.getClass().getSimpleName() + "Addition"; try < Object instance; instance = Class.forName(name).newInstance(); >catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex)

    I’m trying to call the evaluate function of the variable «name» class.

    Here’s the evaluate function.

    public Number evaluate(int left, int right)

    That’s the evaluate method from IntegerIntegerAddition Class

    and I have also the IntegerDoubleAddition Class evaluate method

    public Number evaluate(int left, double right)

    So the variable name could have «IntegerIntegerAddition» or «IntegerDoubleAddition» and I want with both of them call to the Evaluate method with the 2 parameters.

    You’ll want to create a Method object using the name and parameter types that your real method will require. Then you want to use a reference to the object that has that method, and invoke your Method reference on it.

    //These are all the types that my example references will use. Object obj; //The instance that my method is going to be invoked on. Object[] params; //The parameters for my method String nameOfMethod; //The name of my method. Class[] paramTypes; //The types, in order, that my method accepts as parameters Method m = obj.getClass().getMethod(nameOfMethod, paramTypes); //Create my Method object m.invoke(obj, params); //Invoke that method! 

    getMethod() accepts a vararg for the array paramTypes. So you can just list your types directly in there one by one as seperate parameters. Same thing with Method.invoke() for it’s params parameter.

    m.invoke(obj, param1, param2, param3) //etc 

    You could do something like this:

    Method evaluate = instance.getClass().getDeclaredMethod( "evaluate", int.class, int.class ); evaluate.invoke( instance, 3, 1 ); 

    This should find the exact method by parameter type ( alternatively use «int.class, long.class» for your second method ) & invoke it, here using example arguments 3 & 1. Remember to catch the possible exceptions.

    Читайте также:  Currency converter api python

    Java.lang.reflect.Method.invoke() Method Example, Description. The java.lang.reflect.Method.invoke(Object obj, Object args) method invokes the underlying method represented by this Method object, on the specified object with the specified parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both …

    Java Reflection: Create an implementing class

    Class someInterface = Class.fromName("some.package.SomeInterface"); 

    How do I now create a new class that implements someInterface ?

    I need to create a new class, and pass it to a function that needs a SomeInterface as an argument.

    Easily, java.lang.reflect.Proxy to the rescue!

    Full working example :

    interface IRobot < String Name(); String Name(String title); void Talk(); void Talk(String stuff); void Talk(int stuff); void Talk(String stuff, int more_stuff); void Talk(int stuff, int more_stuff); void Talk(int stuff, String more_stuff); >public class ProxyTest < public static void main(String args[]) < IRobot robot = (IRobot) java.lang.reflect.Proxy.newProxyInstance( IRobot.class.getClassLoader(), new java.lang.Class[] < IRobot.class >, new java.lang.reflect.InvocationHandler() < @Override public Object invoke(Object proxy, java.lang.reflect.Method method, Object[] args) throws java.lang.Throwable < String method_name = method.getName(); Class[] classes = method.getParameterTypes(); if (method_name.equals("Name")) < if (args == null) < return "Mr IRobot"; >else < return args[0] + " IRobot"; >> else if (method_name.equals("Talk")) < switch (classes.length) < case 0: System.out.println("Hello"); break; case 1: if (classes[0] == int.class) < System.out.println("Hi. Int: " + args[0]); >else < System.out.println("Hi. String: " + args[0]); >break; case 2: if (classes[0] == String.class) < System.out.println("Hi. String: " + args[0] + ". Int: " + args[1]); >else < if (classes[1] == String.class) < System.out.println("Hi. int: " + args[0] + ". String: " + args[1]); >else < System.out.println("Hi. int: " + args[0] + ". Int: " + args[1]); >> break; > > return null; > >); System.out.println(robot.Name()); System.out.println(robot.Name("Dr")); robot.Talk(); robot.Talk("stuff"); robot.Talk(100); robot.Talk("stuff", 200); robot.Talk(300, 400); robot.Talk(500, "stuff"); > > 

    Creating something which pretends to implement an interface on the fly actually isn’t too hard. You can use java.lang.reflect.Proxy after implementing InvocationHandler to handle any method calls.

    Of course, you could actually generate a real class with a library like BCEL.

    If this is for test purposes, you should look at mocking frameworks like jmock and EasyMock.

    If you want to go beyond interfaces, you might want to take a look at cglib and objenesis. Together, they will allow you to do some pretty powerful stuff, extending an abstract class and instantiating it. (jMock uses them for that purpose, for example.)

    If you want to stick with interfaces, do what Jon Skeet said :).

    Actually, you have to use the class name in Class.fromName() method and cast to your interface type. See if the sample below helps.

    public class Main < public static void main(String[] args) throws Exception < Car ferrari = (Car) Class.forName("Mercedez").newInstance(); System.out.println(ferrari.getName()); >> interface Car < String getName(); >class Mercedez implements Car < @Override public String getName() < return "Mercedez"; >> class Ferrari implements Car < @Override public String getName() < return "Ferrari"; >> 

    Java — GetMethod and invoke it via Reflection passing, The Method.invoke method takes an Object[] parameter which corresponds to the arguments you want to provide. As you’ve got a single parameter which is of type Object[], you need to wrap that in another Object[]. For example: m.invoke(this, new Object[] < new Object[] < tt >>); Or you could use the …

    Источник

    Оцените статью