关于java反射给属性进行赋值的问题!
代码如下:packagecom.itcast.examQuestions.two;importjava.io.FileDescriptor;importjava.lang...
代码如下:
package com.itcast.examQuestions.two;
import java.io.FileDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Person {
String name = "小红";
int age = 22 ;
public static void main(String[] agr)throws Exception{
Constructor constructor1 = Person.class.getConstructor(String.class,int.class);
Object per1 = constructor1.newInstance("小明",2);
//System.out.println(name);
Method methodsn = Person.class.getMethod("setName", String.class);
methodsn.invoke(per1, "小黑");
//System.out.println(name);
ChangeStringVlue(per1);
System.out.println(per1);
}
public static void ChangeStringVlue(Object per1)throws Exception{
Field[] fields = per1.getClass().getFields();
for(Field field:fields)
{
if(field.getType() == String.class){
String oldvalue = (String)field.get(per1);
String newvalue = oldvalue.replaceAll("小红", "小白");
field.set(per1,newvalue);
}
}
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString(){
return name;
}
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;
}
}
以上代码为什么不能给 name属性进行赋值?哪错了? 谢谢您的回答!我都研究好久了。 展开
package com.itcast.examQuestions.two;
import java.io.FileDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Person {
String name = "小红";
int age = 22 ;
public static void main(String[] agr)throws Exception{
Constructor constructor1 = Person.class.getConstructor(String.class,int.class);
Object per1 = constructor1.newInstance("小明",2);
//System.out.println(name);
Method methodsn = Person.class.getMethod("setName", String.class);
methodsn.invoke(per1, "小黑");
//System.out.println(name);
ChangeStringVlue(per1);
System.out.println(per1);
}
public static void ChangeStringVlue(Object per1)throws Exception{
Field[] fields = per1.getClass().getFields();
for(Field field:fields)
{
if(field.getType() == String.class){
String oldvalue = (String)field.get(per1);
String newvalue = oldvalue.replaceAll("小红", "小白");
field.set(per1,newvalue);
}
}
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString(){
return name;
}
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;
}
}
以上代码为什么不能给 name属性进行赋值?哪错了? 谢谢您的回答!我都研究好久了。 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询