Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active July 21, 2016 10:01
Show Gist options
  • Save sunmeat/74182d784183bb7ec8f13f8943447d94 to your computer and use it in GitHub Desktop.
Save sunmeat/74182d784183bb7ec8f13f8943447d94 to your computer and use it in GitHub Desktop.
reflection - method invoke
package reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Student {
private String name;
private int age = (int) (Math.random() * 20 + 20);
public Student(String name) {
setName(name);
}
@Override
public String toString() {
return "Name: " + name + ", 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) {
if (age >= 0 && age <= 100) {
this.age = age;
} else {
this.age = 18;
}
}
}
class Program {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Student s = new Student("Alex");
Class c = s.getClass();
Class[] paramTypes = new Class[]{String.class};
Method method = c.getMethod("setName", paramTypes);
Object[] arg = new Object[]{"Vasya"};
method.invoke(s, arg);
System.out.println(s.getName()); // Vasya
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment