标签:lang main pack logs throw private exception release import
礼悟:
好好学习多思考,尊师重道存感恩。叶见寻根三返一,活水清源藏于零。
虚怀若谷良心主,皓月当空自在王。愿给最苦行无悔,诚劝且行且珍惜。
os :windows7 x64
jdk:jdk-8u131-windows-x64
ide:Eclipse Oxygen Release (4.7.0)
被解析类的代码:
package blog.jizuiku2; /** * * * @author jizuiku * @version V17.10.02 */ public class Person { // 成员变量 public int age; private String password; protected String name; int score; public static int ageStatic=13; private static String passwordStatic="hello world"; protected static String nameStatic; static int scoreStatic; // 构造方法 public Person(int age) {System.out.println("public GZ:int");} public Person(int age,int score) {System.out.println("public GZ:int,int");} private Person() {System.out.println("private GZ:");} protected Person(String name) {System.out.println("protected GZ:String");} Person(int age,String name){this.age=age;this.name=name;System.out.println("default GZ:int,String");} // 成员方法 public void sayHello(String name) {} private int sayHello() {return 1;} protected String sayHello(int age) {return "";} void sayHello(int age,String name) {} public void sayHelloStatic(String name) {} private int sayHelloStatic() {return 1;} protected String sayHelloStatic(int age) {return "";} void sayHelloStatic(int age,String name) {} @Override public String toString() { return "Person [age=" + age + ", password=" + password + ", name=" + name + ", score=" + score + "]"; } }
演示类:
package blog.jizuiku2; import java.lang.reflect.Constructor; import java.lang.reflect.Field; /** * Class 非静态成员变量的获取与设置 * * @author jizuiku * @version V17.10.02 */ public class ClassGetNormalFieldDemo { public static void main(String[] args) throws Exception { String className = "blog.jizuiku2.Person"; Class c = Class.forName(className); // 获取所有的成员变量 System.out.println("该类中所有的成员变量如下:"); Field[] fs = c.getDeclaredFields(); for (Field field : fs) { System.out.println(field); } System.out.println(); // 获取所有的构造方法 System.out.println("该类中所有的构造函数如下:"); Constructor[] cons = c.getDeclaredConstructors(); for (Constructor constructor : cons) { System.out.println(constructor); } System.out.println(); // 使用 blog.jizuiku0.Person(int,java.lang.String) 构造函数 Constructor con = c.getDeclaredConstructor(int.class,java.lang.String.class); // 设置访问权限 con.setAccessible(true); Object obj = con.newInstance(1,"hello"); System.out.println((blog.jizuiku2.Person)obj); // 获取某一成员变量 并 对其赋值 Field passwordField = c.getDeclaredField("password"); // 设置为可以访问 passwordField.setAccessible(true); // 对obj对象的password进行赋值 passwordField.set(obj, "javaer"); System.out.println(passwordField.get(obj)); } }
结果:
Java优秀,值得学习。
学习资源:itcast和itheima视频库。如果您有公开的资源,可以分享给我的话,用您的资源学习也可以。
博文是观看视频后,融入思考写成的。博文好,是老师讲得好。博文坏,是 给最苦 没认真。
JavaSE8基础 Class 获取与设置非静态私有成员变量
标签:lang main pack logs throw private exception release import
原文地址:http://www.cnblogs.com/jizuiku/p/7637706.html