定义一个标准的JavaBean,名叫Person,包含属性name、age。使用反射的方式创建一个实例、调用构造函数初始 10
展开全部
好久没用了算是复习了下:可以正确运行的。
package com.kk.grammar_mechanism.reflect.example2;
import java.io.File;
import java.io.Serializable;
import java.lang.reflect.*;
import java.net.URL;
import java.util.StringTokenizer;
/** 定义一个标准的JavaBean,名叫Person,包含属性name、age。使用反射的方式创建一个实例、调用构造函数初始化 */
public class ReflectTest {
/**
* @param classFullName
* 类的全名称
*/
@SuppressWarnings("unchecked")
public static void execute(String classFullName) {
System.out.println(classFullName + "\n");
try {
// 反射类
Class<?> clazz = Class.forName(classFullName);
// 反射属性字段
Field[] fields = clazz.getDeclaredFields();
// 反射方法
Method[] methods = clazz.getDeclaredMethods();
// 反射构造器
Constructor[] constructors = clazz.getDeclaredConstructors();
for (Field f : fields) {
System.out.println(f);
System.out
.println("修饰符:" + Modifier.toString(f.getModifiers()));
System.out.println("类型:" + f.getType());
System.out.println("属性名:" + f.getName());
}
System.out.println("-----------------------");
for (Method m : methods) {
System.out.println(m.getName());
}
System.out.println("-----------------------");
for (Constructor c : constructors) {
System.out.println(c.getName());
Class[] classs = c.getParameterTypes();
Object o = null;
try {
if (classs.length == 2) {
o = c.newInstance("张三", 12);
} else if (classs.length == 0) {
o = c.newInstance();
} else {
System.out.println("create instance error");
}
} catch (IllegalArgumentException e) {
/**
* Constructor 允许在将实参与带有底层构造方法的形参的 newInstance()
* 匹配时进行扩展转换,但是如果发生 收缩转换 ,则抛出 IllegalArgumentException。
*/
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(o);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
execute(Tool.getClassFullName(Person.class));
}
}
@SuppressWarnings("serial")
class Person implements Serializable {
private String name = "";
private Integer age = 0;
public Person() {
System.out.println("default constructor is called");
}
public Person(String name, Integer age) {
System.out.println("full constructor is called");
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "name : " + this.name + " ; age : " + age;
}
}
@SuppressWarnings("unchecked")
class Tool {
/**
* @return 取得当前类所在的文件
* @param clazz
*/
public static File getClassFile(Class clazz) {
URL path = clazz.getResource(clazz.getName().substring(
clazz.getName().lastIndexOf(".") + 1)
+ ".classs");
if (path == null) {
String name = clazz.getName().replaceAll("[.]", "/");
path = clazz.getResource("/" + name + ".class");
}
return new File(path.getFile());
}
/**
* @return 得到当前类的路径
* @param clazz
*/
public static String getClassFilePath(Class clazz) {
try {
return java.net.URLDecoder.decode(getClassFile(clazz)
.getAbsolutePath(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* @return 取得当前类所在的ClassPath目录,比如tomcat下的classes路径
* @param clazz
*/
public static File getClassPathFile(Class clazz) {
File file = getClassFile(clazz);
for (int i = 0, count = clazz.getName().split("[.]").length; i < count; i++)
file = file.getParentFile();
if (file.getName().toUpperCase().endsWith(".JAR!")) {
file = file.getParentFile();
}
return file;
}
/**
* @return 取得当前类所在的ClassPath路径
* @param clazz
*/
public static String getClassPath(Class clazz) {
try {
return java.net.URLDecoder.decode(getClassPathFile(clazz)
.getAbsolutePath(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* @return 取得当前类的完整名称
* @param clazz
*/
public static String getClassFullName(Class clazz) {
String classFilePath = getClassFilePath(clazz);
String classPath = getClassPath(clazz);
StringTokenizer stk = new StringTokenizer(classFilePath
.substring(classPath.length() + 1), "\\");
StringBuffer sb = new StringBuffer();
int hight = stk.countTokens();
while (stk.hasMoreTokens()) {
if (hight > 1) {
sb.append(stk.nextToken()).append(".");
} else {
sb.append(stk.nextToken());
}
--hight;
}
String temp = sb.toString();
return temp.substring(0, temp.length() - ".class".length());
}
}
---------------------------------------以下是执行结果------------------------------------------
com.kk.grammar_mechanism.reflect.example2.Person
private java.lang.String com.kk.grammar_mechanism.reflect.example2.Person.name
修饰符:private
类型:class java.lang.String
属性名:name
private java.lang.Integer com.kk.grammar_mechanism.reflect.example2.Person.age
修饰符:private
类型:class java.lang.Integer
属性名:age
-----------------------
getAge
setAge
toString
getName
setName
-----------------------
com.kk.grammar_mechanism.reflect.example2.Person
default constructor is called
name : ; age : 0
com.kk.grammar_mechanism.reflect.example2.Person
full constructor is called
name : 张三 ; age : 12
package com.kk.grammar_mechanism.reflect.example2;
import java.io.File;
import java.io.Serializable;
import java.lang.reflect.*;
import java.net.URL;
import java.util.StringTokenizer;
/** 定义一个标准的JavaBean,名叫Person,包含属性name、age。使用反射的方式创建一个实例、调用构造函数初始化 */
public class ReflectTest {
/**
* @param classFullName
* 类的全名称
*/
@SuppressWarnings("unchecked")
public static void execute(String classFullName) {
System.out.println(classFullName + "\n");
try {
// 反射类
Class<?> clazz = Class.forName(classFullName);
// 反射属性字段
Field[] fields = clazz.getDeclaredFields();
// 反射方法
Method[] methods = clazz.getDeclaredMethods();
// 反射构造器
Constructor[] constructors = clazz.getDeclaredConstructors();
for (Field f : fields) {
System.out.println(f);
System.out
.println("修饰符:" + Modifier.toString(f.getModifiers()));
System.out.println("类型:" + f.getType());
System.out.println("属性名:" + f.getName());
}
System.out.println("-----------------------");
for (Method m : methods) {
System.out.println(m.getName());
}
System.out.println("-----------------------");
for (Constructor c : constructors) {
System.out.println(c.getName());
Class[] classs = c.getParameterTypes();
Object o = null;
try {
if (classs.length == 2) {
o = c.newInstance("张三", 12);
} else if (classs.length == 0) {
o = c.newInstance();
} else {
System.out.println("create instance error");
}
} catch (IllegalArgumentException e) {
/**
* Constructor 允许在将实参与带有底层构造方法的形参的 newInstance()
* 匹配时进行扩展转换,但是如果发生 收缩转换 ,则抛出 IllegalArgumentException。
*/
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(o);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
execute(Tool.getClassFullName(Person.class));
}
}
@SuppressWarnings("serial")
class Person implements Serializable {
private String name = "";
private Integer age = 0;
public Person() {
System.out.println("default constructor is called");
}
public Person(String name, Integer age) {
System.out.println("full constructor is called");
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "name : " + this.name + " ; age : " + age;
}
}
@SuppressWarnings("unchecked")
class Tool {
/**
* @return 取得当前类所在的文件
* @param clazz
*/
public static File getClassFile(Class clazz) {
URL path = clazz.getResource(clazz.getName().substring(
clazz.getName().lastIndexOf(".") + 1)
+ ".classs");
if (path == null) {
String name = clazz.getName().replaceAll("[.]", "/");
path = clazz.getResource("/" + name + ".class");
}
return new File(path.getFile());
}
/**
* @return 得到当前类的路径
* @param clazz
*/
public static String getClassFilePath(Class clazz) {
try {
return java.net.URLDecoder.decode(getClassFile(clazz)
.getAbsolutePath(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* @return 取得当前类所在的ClassPath目录,比如tomcat下的classes路径
* @param clazz
*/
public static File getClassPathFile(Class clazz) {
File file = getClassFile(clazz);
for (int i = 0, count = clazz.getName().split("[.]").length; i < count; i++)
file = file.getParentFile();
if (file.getName().toUpperCase().endsWith(".JAR!")) {
file = file.getParentFile();
}
return file;
}
/**
* @return 取得当前类所在的ClassPath路径
* @param clazz
*/
public static String getClassPath(Class clazz) {
try {
return java.net.URLDecoder.decode(getClassPathFile(clazz)
.getAbsolutePath(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* @return 取得当前类的完整名称
* @param clazz
*/
public static String getClassFullName(Class clazz) {
String classFilePath = getClassFilePath(clazz);
String classPath = getClassPath(clazz);
StringTokenizer stk = new StringTokenizer(classFilePath
.substring(classPath.length() + 1), "\\");
StringBuffer sb = new StringBuffer();
int hight = stk.countTokens();
while (stk.hasMoreTokens()) {
if (hight > 1) {
sb.append(stk.nextToken()).append(".");
} else {
sb.append(stk.nextToken());
}
--hight;
}
String temp = sb.toString();
return temp.substring(0, temp.length() - ".class".length());
}
}
---------------------------------------以下是执行结果------------------------------------------
com.kk.grammar_mechanism.reflect.example2.Person
private java.lang.String com.kk.grammar_mechanism.reflect.example2.Person.name
修饰符:private
类型:class java.lang.String
属性名:name
private java.lang.Integer com.kk.grammar_mechanism.reflect.example2.Person.age
修饰符:private
类型:class java.lang.Integer
属性名:age
-----------------------
getAge
setAge
toString
getName
setName
-----------------------
com.kk.grammar_mechanism.reflect.example2.Person
default constructor is called
name : ; age : 0
com.kk.grammar_mechanism.reflect.example2.Person
full constructor is called
name : 张三 ; age : 12
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询