package test.mylo.basic.Test3; /** * @program: workSet * @description: * @author: Mylo * @create: 2018-09-30 08:27 **/ public class Student { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } int getAge() { return age; } void setAge(int age) { this.age = age; } } |
public class Test1 { public static void main(String[] args) throws Exception { Student s = new Student(); s.setAge(18); System.out.println(s); } } |
根据上述得出总结:首先我们要调用无参构造去创建对象,然后,使用对象去调用方法,掉你用方法的时候,对应传递参数,如果是一个重载的方法,还可以根据方法上的参数去对应调用重载方法 |
Student s = new Student(); Class<? extends Student> aClass = s.getClass(); Class<? extends Student> bClass = Student.class;//推荐使用类全名的方式获取,很多框架都是根据这种方式创建对象 Class c = Class.forName("test.mylo.basic.Test3.Student"); System.out.println(aClass == bClass); System.out.println( c == bClass); |
1.1获取构造方法
|
//new 新的 / 新建 Instance 实例Object obj = cons.newInstance(); |
// getMethod 只能获取使用public 修饰的方法 //getDeclaredMethod 这个 无视修饰符 //参数1:方法名, 参数2:参数类型 Method setAge = c.getDeclaredMethod("setAge", int.class); |
//invoke 执行 setAge.invoke(obj,19); //getAge Method getAge = c.getDeclaredMethod("getAge"); Object age = getAge.invoke(obj); |
//Field 字段//cannot access a member of class test.mylo.basic.Test3.Student with modifiers "private" Field name = c.getDeclaredField("name"); name.setAccessible(true); name.set(obj,"test"); System.out.println(name.get(obj)); |
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |