Java virtual method call

What is virtual method calling in java?

That means, that the object’s dynamic type is «chosing» which method will be invoked, and not the static type.

class A < public void foo() < >> class B extends A < public void foo() < >> 

B.foo() will be invoked, and NOT A.foo() , since the dynamic type of obj is B .

Solution 2

we mean that in java applications the executed method is determined by the object type in run time

interface Animal < public void eat(); >class Person implements Animal < public void eat()< System.out.println("Eating Food");>> class Eagle implements Animal < public void eat()< System.out.println("Eating Snake");>> 
Animal animal = new Person(); animal.eat(); //it will print eating food animal = new Eagle(); animal.eat(); //it will print eating snake 

Solution 3

Suppose you have a class Fruit, with two subclasses Orange and Banana. And suppose that Fruit has a String getColor() method.

Orange can override the getColor() method to return «orange». Same for Banana, which can have it return «yellow».

When some method uses an object of type Fruit, and call the getColor() method, the method that will be called is Banana.getColor() if the type of the Fruit is in fact Banana.

 private void printColor(Fruit f) < System.out.println(f.getColor()); >. Fruit fruit1 = new Banana(); Fruit fruit2 = new Orange(); printColor(fruit1); // prints yellow printColor(fruit2); // prints orange 

Solution 4

Employee.java

public class Employee < private String name; private String address; private int number; public Employee(String name, String address, int number) < System.out.println("Constructing an Employee"); this.name = name; this.address = address; this.number = number; >public void mailCheck() < System.out.println("Mailing a check to " + this.name + " " + this.address); >> 

VirtualMethod.java

class Salary extends Employee < private double salary; //Annual salary public Salary(String name, String address, int number, double salary) < super(name, address, number); this.salary=salary; >public void mailCheck() < System.out.println("Within mailCheck of Salary class "); System.out.println("Mailing check to " + " with salary " + salary); >> public class VirtualMethod < public static void main(String [] args) < Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00); Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00); System.out.println("Call mailCheck using Salary reference --"); s.mailCheck(); System.out.println("\n Call mailCheck using Employee reference--"); e.mailCheck(); >> 
Constructing an Employee Constructing an Employee Call mailCheck using Salary reference -- Within mailCheck of Salary class Mailing check to with salary 3600.0 Call mailCheck using Employee reference-- Within mailCheck of Salary class Mailing check to with salary 2400.0 

Explanation

here, we instantiate two Salary objects. One using a Salary reference s , and the other using an Employee reference e .

While invoking s.mailCheck() the compiler sees mailCheck() in the Salary class at compile time, and the JVM invokes mailCheck() in the Salary class at run time.

Invoking mailCheck() on e is quite different because e is an Employee reference. When the compiler sees e.mailCheck() , the compiler sees the mailCheck() method in the Employee class.

Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run time, however, the JVM invokes mailCheck() in the Salary class.

Источник

What is the use of Java virtual method invocation?

Solution 2: Assuming you only want to to do it for 3 methods, you can do something like this: and your method should look something like this: Now this won’t be as good if you want to do it for many more methods but nevertheless if you want to do it you can create a method that returns all possible permutations of an array of size where is the number of methods you wanna execute this way. is what you index into with the argument, and the arrays it contains are the methods to call in the order in which you want to call them.

What is the use of Java virtual method invocation?

I understand what is java method invocation and have practiced many examples using it.

I want to know what is the practical situation or need of this concept. It would be of great help if anyone could give a real world scenario where it is used and what would happen if this concept would have not been there?

Here is an example. Suppose we have 2 classes:

class A < public String getName() < return "A"; >> class B extends A < public String getName() < return "B"; >> 

If we now do the following:

public static void main(String[] args)

If Java didn’t have virtual method invocation , it would determine at compile time that the getName() to be called is the one that belongs to the A class. Since it doesn’t, but determines this at runtime depending on the actual class that myA points to, we get the above result.

[EDIT to add (slightly contrived) example]
You could use this feature to write a method that takes any number of Object s as argument and prints them like this:

public void printObjects(Object. objects) < for (Object o: objects) < System.out.println(o.toString()); >> 

This will work for any mix of Objects. If Java didn’t have virtual method invocation , all Objects would be printed using Object´s toString() which isn’t very readable. Now instead, the toString() of each actual class will be used, meaning that the printout will usually be much more readable.

OK, I’ll try to provide a simple example. You are writing a method that will fill a caller-supplied list:

Now, one caller wants to use a linked list; another one prefers a list implementation based on an array. There will be other callers with even more list implementations that you’ve never even heard of. These are totally different objects. Propose a solution that achieves this without relying on virtual methods .

Without virtual methods this would mean that the type List would already need to have the method add implemented. Even if you had a subtype ArrayList which had an overridden method, the compiler (and the runtime!) would simply ignore that method and use the one in List . It would be impossible to use different List implementations that conform to the same interface; it would be impossible to reuse that line of code in the method fill since it would work only with the method in the type List .

So you see, the whole idea of type hierarchy wouldn’t make a lot of sense; interface s and abstract class es couldn’t even exist. The whole of Java would break down into shards without that one feature of virtual methods.

Java measure method invocation rate, Show activity on this post. I want to calculate and print method invocation rate, let’s say I have the following method that is called on every consumed message (from Kafka): public class Consumer < public void run () < while (true) < ConsumerRecordsrecs = consumer.poll (); for (ConsumerRecord …

Java, Reflection, and method invocation

I am having issue with reflection and calling only specific methods. In my case I want to call the method getMyStuff() which may defined in more than one Class.

My classes look similar to this. MainClass will always be the parent. I have a LOT of classes and not all the classes have the getMyStuff() method. I want to be able to call that method and access the return value. I have tried many incarnations of code to get access but nothing seems to work.

class MainClass < public ClassA member1; public String getMyStuff() <>> class ClassA < public ClassB member1; public String getMyStuff() <>> class ClassB < public String getMyStuff() <>> 

You can invoke the method using reflection like this:

public static String getMyStuff(Object o) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException < Classcl = o.getClass(); Method m = cl.getMethod("getMyStuff"); return (String) m.invoke(o); > 

However it would be far easier to add the method to an interface and implement this interface with the classes

public interface MyStuffContainer < public String getMyStuff(); >class ClassA implements MyStuffContainer < public ClassB member1; public String getMyStuff() <>> public static String getMyStuff(Object o)

The static getMyStuff method is called like this in both cases:

getMyStuff(new MainClass()); getMyStuff(new ClassA()); getMyStuff(new ClassB()); 

Why don’t you extend from MainClass and override getMyStuff() where needed?

First go over your class and check if the class have the method you want:

Class c = ob.getClass(); for (Method method : c.getDeclaredMethods()) < System.out.println(method.getName()); // check for the getMyStuff() method >

if the method exist create an instance of that class and call the method:

Class clazz = Class.forName(className); Constructor ctor = clazz.getConstructor(String.class); Object object = ctor.newInstance(new Object[] < ctorArgument >); 

I solved it today. The main thing I had issue with was how to grab/access the objects in ClassA and ClassB. I was thinking you needed to iterate over the object somehow and access each object in turn. However Reflection has a different paradigm. You iterate over all the fields via getDeclaredFields(). Once you get a Field object for the field «Field field = aClass.getField(«someField»);» you then need to use the Field object to access the underlying object for that field «Object value = field.get(objectValue);»

I know this is not so good explanation but essentially I did not understand that you had to access the field first, pass in the object that the field is within, then «field.get(objectValue)» looks inside that objectValue and returns the object with that field name. Kinda reverse on how I think.

Does Java support dynamic method invocation?, There are three supported invocations modes : invokestatic, invokespecial, invokeinterface or invokevirtual. These modes allows to call methods with known signature. We talk of strongly typed language. This allows to to make some checks directly at compile time. On the other side, the dynamic languages …

How to identify if an expression is ‘method invocation’?

Consider the method invocation expression below :

The function foo takes three arguments, where the third argument is the value returned by the function, bar . Now suppose, I need to find out whether the expression inside the parentheses is a method invocation or not. For the above cases, I should report bar() .

foo(1, foobar(0, 1), A.staticMethod(1)), 

I should report foobar(0, 1) and A.staticMethod(1) , where A is a class having the static function, staticMethod(int) . Is there any way or a fail-safe regex that will be applicable for this case ?

Following are the other cases which should be reported as well :

new A().foo() a.foo() // A a = new A(); a.bar().field // bar() returns an object here 

I am open to using any parsing APIs like ANTLR as well.

Also, as mentioned in one of the comments, I want to clarify that the only input is the expression and nothing else, not the source code (and hence, no comments or something else I should ignore).

Assuming there are no syntax errors in the input, you can simply define a method invocation as an identifier ( [A-Za-z_]\w* ) followed by a parenthesized set of arguments, with the added condition that it is not preceded by te keyword new (since your syntax supports instance creation).

public static List methodCalls(String input) < Listmatches = new ArrayList<>(); Pattern p = Pattern.compile("\\s*[A-Za-z_]\\w*\\s*\\("); Matcher m = p.matcher(input); while (m.find()) < int start = m.start(); int end = m.end(); if (start == 3 && input.startsWith("new") || start >3 && input.substring(start-4, start).matches("\\Wnew")) < // if it is preceded by the word new, it is not a method call continue; >int pairs = 1; while (end < input.length() && pairs >0) < // can't just stop at the next ')' // since parentheses may be nested char c = input.charAt(end); if (c == '(') pairs++; else if (c == ')') pairs--; end++; >matches.add(input.substring(start, end)); > return matches; > 

Java Method invoke() Method with Examples, The invoke () method of Method class Invokes the underlying method represented by this Method object, on the specified object with the specified parameters. Individual parameters automatically to match primitive formal parameters. Both primitive and reference parameters are subject to method invocation …

Method invocation order

Suppose I have a method which contains invocation of 3 another methods. How can I set invocation order of internal methods depends on parameter? For instance,

public void method(int i) < if(i == 0)< anotherMethod1(); anotherMethod2(); anotherMethod3(); >else if(i == 1) < anotherMethod2(); anotherMethod1(); anotherMethod3(); >else if(i == 2) < anotherMethod3(); anotherMethod2(); anotherMethod1(); >//ETC 

Is there a way to do it without multiple if-else clauses?

You’ve said you’re using Java 5 (!), so Java 8’s lambdas are out.

You pretty much have three choices:

  1. if/else if/else if as in your example.
  2. switch , which is similar.
  3. A Map (or array) of arrays of interface references, where you implement the interface by calling each of your methods. The outer Map /array is what you index into with the argument, and the arrays it contains are the methods to call in the order in which you want to call them. E.g., a dispatch map that gives you a list of the methods in the right order, wrapped in an interface so you store references to them.
  4. #3, but using reflection instead, so the inner arrays are arrays of Method .

#3 and #4 are almost certainly way over the top.

Assuming you only want to to do it for 3 methods, you can do something like this:

int[][] orderOfExecution = ,,,,,>; void executeMethod(int x) < switch(x)< case 1: anotherMethod1(); break; case 2: anotherMethod2(); break; case 3: anotherMethod3(); break; >> 

and your method() method should look something like this:

Now this won’t be as good if you want to do it for many more methods but nevertheless if you want to do it you can create a method that returns all possible permutations of an array of size n where n is the number of methods you wanna execute this way.

Java, Reflection, and method invocation, 0. First go over your class and check if the class have the method you want: Class c = ob.getClass (); for (Method method : c.getDeclaredMethods ()) < System.out.println (method.getName ()); // check for the getMyStuff () method >if the method exist create an instance of that class and call the method:

Источник

Читайте также:  Найти только числа python
Оцените статью