java中的反射 (二)

2014-11-24 10:09:12 · 作者: · 浏览: 1
;
String newValue = oldValue.replace('b', 'a');
field.set(obj, newValue);
}
}

}

}


class TestArguments{
public static void main(String[] args){
for(String arg : args){
System.out.println(arg);
}
}
}


-----------------------------------

package cn.itcast.day1;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Properties;

public class ReflectTest2 {

/**
* @param args
*/
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
/*getRealPath();//金山词霸/内部
一定要记住用完整的路径,但完整的路径不是硬编码,而是运算出来的。*/
//InputStream ips = new FileInputStream("config.properties");

//InputStream ips = ReflectTest2.class.getClassLoader().getResourceAsStream("cn/itcast/day1/config.properties");
//InputStream ips = ReflectTest2.class.getResourceAsStream("resources/config.properties");
InputStream ips = ReflectTest2.class.getResourceAsStream("/cn/itcast/day1/resources/config.properties");

Properties props = new Properties();
props.load(ips);
ips.close();
String className1 = props.getProperty("className");
Collection collections = (Collection)Class.forName(className1).newInstance();

//Collection collections = new HashSet();
ReflectPoint pt1 = new ReflectPoint(3,3);
ReflectPoint pt2 = new ReflectPoint(5,5);
ReflectPoint pt3 = new ReflectPoint(3,3);

collections.add(pt1);
collections.add(pt2);
collections.add(pt3);
collections.add(pt1);

//pt1.y = 7;
//collections.remove(pt1);

System.out.println(collections.size());
}

}


----------------------------------------------

package cn.itcast.day1;

import java.util.Date;

public class ReflectPoint {
private Date birthday = new Date();

private int x;
public int y;
public String str1 = "ball";
public String str2 = "basketball";
public String str3 = "itcast";

public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}


@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ReflectPoint other = (ReflectPoint) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}


@Override
public String toString(){
return str1 + ":" + str2 + ":" + str3;
}


public int getX() {
return x;
}


public void setX(int x) {
this.x = x;
}


public int getY() {
return y;
}


public void setY(int y) {
this.y = y;
}


public Date getBirthday() {
return birthday;
}


public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}