「Java入門」Javaのクラスを勉強するサンプルプログラム

1.ReflectPoint.java
コード下記:
package startnews24;
public class ReflectPoint {
public int x;
public int y;
public String str1="東京";
public String str2="川崎";
public String str3="埼玉";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
public String toString(){
return str1+":"+str2+":"+str3;
}

}

2.ReflectStartnews24.java
コード下記
package startnews24;

import java.lang.reflect.Field;

public class ReflectStartnews24 {

/**
* @param args
* @throws ClassNotFoundException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
// TODO Auto-generated method stub
String str1="大船";
Class cls1=str1.getClass();
Class cls2=String.class;
Class cls3=Class.forName(“java.lang.String");
System.out.println(cls1==cls2);
System.out.println(cls1==cls3);

ReflectPoint pt1=new ReflectPoint(3,5);
Field fieldY=pt1.getClass().getField(“y");
System.out.println(fieldY.get(pt1));
Field fieldX=pt1.getClass().getField(“x");
System.out.println(fieldX.get(pt1));

changeStringValue(pt1);
System.out.println(pt1);

}

private static void changeStringValue(ReflectPoint pt1) throws IllegalArgumentException, IllegalAccessException {
// TODO Auto-generated method stub
Field[] fields=pt1.getClass().getFields();/*get the public field with the given name*/
for(Field field:fields)
{
if(field.getType()==String.class){
String oldValue=(String)field.get(pt1);
String newValue=oldValue.replace(“b", “a");
field.set(pt1, newValue);
}
}
}

}

Java

Posted by arkgame