Created
July 11, 2020 13:31
-
-
Save railroadman/094241200dc723cc67247973c6a8ecd8 to your computer and use it in GitHub Desktop.
Работа с java reflect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mypackage.bean; | |
public class Dog { | |
private String name; | |
private int age; | |
public Dog() { | |
// empty constructor | |
} | |
public Dog(String name, int age) { | |
this.name = name; | |
this.age = age; | |
} | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public int getAge() { | |
return age; | |
} | |
public void setAge(int age) { | |
this.age = age; | |
} | |
public void printDog(String name, int age) { | |
System.out.println(name + " is " + age + " year(s) old."); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mypackage.demo; | |
import java.lang.reflect.*; | |
public class ReflectionDemo { | |
public static void main(String[] args) throws Exception { | |
String dogClassName = "com.mypackage.bean.Dog"; | |
Class<?> dogClass = Class.forName(dogClassName); // convert string classname to class | |
Object dog = dogClass.newInstance(); // invoke empty constructor | |
String methodName = ""; | |
// with single parameter, return void | |
methodName = "setName"; | |
Method setNameMethod = dog.getClass().getMethod(methodName, String.class); | |
setNameMethod.invoke(dog, "Mishka"); // pass arg | |
// without parameters, return string | |
methodName = "getName"; | |
Method getNameMethod = dog.getClass().getMethod(methodName); | |
String name = (String) getNameMethod.invoke(dog); // explicit cast | |
// with multiple parameters | |
methodName = "printDog"; | |
Class<?>[] paramTypes = {String.class, int.class}; | |
Method printDogMethod = dog.getClass().getMethod(methodName, paramTypes); | |
printDogMethod.invoke(dog, name, 3); // pass args | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment