Get object parameters java

Java Object as Parameter

Objects, like primitive types, can be passed as parameters to methods in Java. When passing an object as a parameter to a method, a reference to the object is passed rather than a copy of the object itself. This means that any modifications made to the object within the method will have an impact on the original object.

The general form to demonstrate «object as parameter» in Java is as follows:

public class MyClass < // Fields or attributes private int attribute1; private String attribute2; private double attribute3; // Constructor public MyClass(int attribute1, String attribute2, double attribute3) < this.attribute1 = attribute1; this.attribute2 = attribute2; this.attribute3 = attribute3; >// Method with object as parameter public void myMethod(MyClass obj) < // block of code to define this method > // More methods >

An object belonging to the «MyClass» class is used as a parameter in the myMethod() function. This enables the method to operate on the passed object and access its attributes and methods.

Java objects as parameters example

Consider the following program demonstrating the object as parameters in Java:

public class MyClass < private int attribute1; private String attribute2; private double attribute3; // Constructor public MyClass(int attribute1, String attribute2, double attribute3) < this.attribute1 = attribute1; this.attribute2 = attribute2; this.attribute3 = attribute3; >// Method with object as parameter public void myMethod(MyClass obj) < System.out.println("Attribute 1: " + obj.attribute1); System.out.println("Attribute 2: " + obj.attribute2); System.out.println("Attribute 3: " + obj.attribute3); >public static void main(String[] args) < MyClass myObject1 = new MyClass(10, "Hello", 3.14); MyClass myObject2 = new MyClass(20, "World", 6.28); // Call the method with object as parameter myObject1.myMethod(myObject2); > >
Attribute 1: 20 Attribute 2: World Attribute 3: 6.28

The class MyClass in this code has three attributes labeled attribute1, attribute2, and attribute3 and a constructor that accepts three parameters. The class also includes a method called myMethod, which accepts as a parameter an object of the same class MyClass. The attributes of the passed object are printed using System.out.println() statements within the method. In the main() method, two MyClass objects are constructed using the constructor, and then the myMethod() method of the first object is invoked with the second object as a parameter. This results in the output of the attributes of the second object to the console.

Читайте также:  Document

Before closing the discussion on «object as parameters» in Java, I wanted to include another example, which is given below, that might help you more with the topic.

public class ObjectAsParameterExample < public static void main(String[] args) < MyClass myObject1 = new MyClass("Edwin", 32); MyClass myObject2 = new MyClass("William", 29); // Call the method that takes a MyClass object as a parameter printPersonInfo(myObject1); // Call the method that takes two MyClass objects as parameters printBothPersonsInfo(myObject1, myObject2); > // Method that takes a MyClass object as a parameter public static void printPersonInfo(MyClass person) < System.out.println("Name: " + person.getName()); System.out.println("Age: " + person.getAge()); >// Method that takes two MyClass objects as parameters public static void printBothPersonsInfo(MyClass myObject1, MyClass myObject2) < System.out.println("\n---Person 1---"); System.out.println("Name: " + myObject1.getName()); System.out.println("Age: " + myObject1.getAge()); System.out.println("\n---Person 2---"); System.out.println("Name: " + myObject2.getName()); System.out.println("Age: " + myObject2.getAge()); >> class MyClass < private String name; private int age; public MyClass(String name, int age) < this.name = name; this.age = age; >public String getName() < return name; >public int getAge() < return age; >>
Name: Edwin Age: 32 ---Person 1--- Name: Edwin Age: 32 ---Person 2--- Name: William Age: 29

The printPersonInfo() and printBothPersonsInfo() methods of the ObjectAsParameterExample class accept MyClass objects as parameters. The printPersonInfo() method prints a single person’s name and age, whereas the printBothPersonsInfo() method prints the names and ages of two people.

The constructor is used to create two MyClass objects in the main() method, and then the printPersonInfo() method is called to print the information of the first object. Finally, the printBothPersonsInfo() method is invoked with both objects as parameters to print both objects’ information.

Liked this article? Share it!

Источник

Tech Tutorials

Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.

Sunday, December 29, 2019

Reflection in Java — Getting Method Information

Reflection in Java class gives a good idea about how class is an entry point to all the Reflection APIs. Once you have Class object you can get information about members of the class like fields, constructors, methods. In this post we’ll see how you can get method information using Java Reflection API.

Member Interface in Java Reflection API

With in the Reflection hierarchy an interface java.lang.reflect.Member is defined which is implemented by java.lang.reflect.Field, java.lang.reflect.Method, and java.lang.reflect.Constructor classes. Thus Member is an interface that reflects identifying information about a single member (a field or a method) or a constructor.

This post talks about Method class and how it can be used to get information about methods using reflection. Class methods have return values, parameters, and may throw exceptions. The java.lang.reflect.Method class provides methods for obtaining the type information for the parameters and return value. It may also be used to invoke methods on a given object.

How to get Method object

  • getMethod(String name, Class. parameterTypes)— Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.
  • getMethods()— Returns an array containing Method objects reflecting all the public methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
  • getDeclaredMethod(String name, Class. parameterTypes)— Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
  • getDeclaredMethods()— Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Getting method information using Java reflection example

As a preparation for the example code let’s have a class called Parent.java which will be extended by the class ChildClass.java which is the class we are going to examine. There is also an interface IntTest.java which is implemented by ChildClass.java.

public class Parent < String name; Parent(String name)< this.name = name; >public void displayName(String name) < System.out.println("Hello - " + name); >public String getName() < return name; >>
public class ChildClass extends Parent implements IntTest < private int value; //Constructor public ChildClass(String name, int value) < super(name); this.value = value; >@Override public void showValue() < System.out.println("Value - " + value); >>

Now let’s see how you can get method information using all the four methods mentioned above.

import java.lang.reflect.Method; import java.util.Arrays; public class ReflectMethod < public static void main(String[] args) < try < // Getting Class instance Classc = Class.forName("org.netjs.prog.ChildClass"); // Using getMethod(methodName, parameters) Method method = c.getMethod("displayName", String.class); System.out.println("Method params " + Arrays.toString(method.getParameters())); // Will throw exception /*method = c.getDeclaredMethod("displayName", String.class); System.out.println("Method params " + Arrays.toString(method.getParameters()));*/ Method[] methodArr = c.getMethods(); System.out.println("All methods " + Arrays.toString(methodArr)); methodArr = c.getDeclaredMethods(); System.out.println("Class methods " + Arrays.toString(methodArr)); > catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) < // TODO Auto-generated catch block e.printStackTrace(); >> >
Method params [java.lang.String arg0] All methods [public void org.netjs.prog.ChildClass.showValue(), public java.lang.String org.netjs.prog.Parent.getName(), public void org.netjs.prog.Parent.displayName(java.lang.String), public final void java.lang.Object.wait() throws java.lang.InterruptedException, public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException, public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException, public boolean java.lang.Object.equals(java.lang.Object), public java.lang.String java.lang.Object.toString(), public native int java.lang.Object.hashCode(), public final native java.lang.Class java.lang.Object.getClass(), public final native void java.lang.Object.notify(), public final native void java.lang.Object.notifyAll()] Class methods [public void org.netjs.prog.ChildClass.showValue()]

First call to the getMethod with parameters method name and parameter types returns the matching method. Then parameters of the method are printed using the getParameters() method of the Method class.

Second call (Which is commented) will throw NoSuchMethodException as the method displayName is inherited from the parent class and getDeclaredMethod() will work for the methods with in the class.

getMethods() will return all the methods of the class and also the inherited methods.

GetDeclaredMethods() will return all the methods of the class but not the inherited one.

Getting method parameter types and return type using reflection

If we have a class called ChildClass as follows then we can get its method parameter types and return type using reflection.

public class ChildClass extends Parent implements IntTest < private int value; //Constructor public ChildClass(String name, int value) < super(name); this.value = value; >@Override public void showValue() < System.out.println("Value - " + value); >public String getValue(String name) throws Exception < return "Hello" + name; >>

// Getting Class instance Class c = Class.forName(«org.netjs.prog.ChildClass»); methodArr = c.getDeclaredMethods(); for(Method m: methodArr)

For Method - getValue Parameter types are - [class java.lang.String] For Method - getValue Return type class java.lang.String For Method - showValue Parameter types are - [] For Method - showValue Return type void

Getting method modifiers using reflection

If you want to get information about the modifiers of the methods of the class you can use getModifiers() method whose return type is int.

// Getting Class instance Class c = Class.forName(«org.netjs.prog.ChildClass»); methodArr = c.getDeclaredMethods(); for(Method m: methodArr)

For Method - getValue modifier is – public For Method - showValue modifier is – public

Getting thrown exceptions using reflection

If you want to get information about types of exceptions declared to be thrown by the methods of the class you can use getExceptionTypes() method.

// Getting Class instance Class c = Class.forName(«org.netjs.prog.ChildClass»); methodArr = c.getDeclaredMethods(); for(Method m: methodArr)

For Method - getValue Thrown Exceptions - [class java.lang.Exception] For Method - showValue Thrown Exceptions - []

Invoking method using reflection

Using Java reflection API you can also invoke methods on a class at runtime. Methods are invoked using java.lang.reflect.Method.invoke() method. The first argument is the object instance on which this particular method is to be invoked. (If the method is static, the first argument should be null.) Subsequent arguments are the method’s parameters.

// Getting Class instance Class c = Class.forName("org.netjs.prog.ChildClass"); // Getting class object ChildClass ch = new ChildClass("Test", 10); Method method = c.getDeclaredMethod("getValue", String.class); try < String result = (String)method.invoke(ch, "Reflection"); System.out.println("Method invocation returned - " + result); >catch (IllegalAccessException e) < // TODO Auto-generated catch block e.printStackTrace(); >catch (IllegalArgumentException e) < // TODO Auto-generated catch block e.printStackTrace(); >catch (InvocationTargetException e) < // TODO Auto-generated catch block e.printStackTrace(); >
Method invocation returned – HelloReflection

Invoking private method of the class using reflection

You can even invoke the private method of the class using reflection in Java. Using getDeclaredMethod() you can get even the private method of the class.

Once you have the method object you can use the setAccessible() method which is inherited from class java.lang.reflect.AccessibleObject to set the access for the private method as true at run time and then invoke it from another class.

Let’s say we have a ChildClass as follows with a private method getValue().

public class ChildClass extends Parent implements IntTest < private int value; //Constructor public ChildClass(String name, int value) < super(name); this.value = value; >@Override public void showValue() < System.out.println("Value - " + value); >private String getValue(String name) throws Exception < return "Hello" + name; >>

Now you want to invoke this private method.

// Getting Class instance Class c = Class.forName("org.netjs.prog.ChildClass"); // Getting class object ChildClass ch = new ChildClass("Test", 10); Method method = c.getDeclaredMethod("getValue", String.class); method.setAccessible(true); try < String result = (String)method.invoke(ch, "Reflection"); System.out.println("Method invocation returned - " + result); >catch (IllegalAccessException e) < // TODO Auto-generated catch block e.printStackTrace(); >catch (IllegalArgumentException e) < // TODO Auto-generated catch block e.printStackTrace(); >catch (InvocationTargetException e) < // TODO Auto-generated catch block e.printStackTrace(); >
Method invocation returned – HelloReflection

You can comment the line where access to the method is set as true.

Then if you execute it you will get the exception as follows —

java.lang.IllegalAccessException: Class org.netjs.prog.ReflectMethod can not access a member of class org.netjs.prog.ChildClass with modifiers "private" at sun.reflect.Reflection.ensureMemberAccess(Unknown Source) at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source) at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.netjs.prog.ReflectMethod.main(ReflectMethod.java:32)

That’s all for this topic Reflection in Java — Getting Method Information. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Источник

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