代码如下:
package cn.itcast.day1;
import java.lang.reflect.*;
public class ReflectTest3 {
public static void main(String[] args) throws Exception {
String startingClassName = args[0];
Method methodMain = Class.forName(startingClassName).getMethod("main",
String[].class);
methodMain.invoke(null,
(Object) new String[] { "haha", "hehe", "xixi" });
}
}
class ReflectArguments {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg);
}
}
}
分析代码:
在Argument中加入语句cn.itcast.day1.ReflectArguments即可运行。
在实际开发中还有另一种情况,就是要从配置文件中提取数据来参与到代码运算中来,先看一段代码,然后再来分析:
package cn.itcast.day1;
import java.util.*;
import java.io.*;
public class ReflectTest2 {
public static void main(String[] args) throws Exception {
InputStream ips = ReflectTest2.class
.getResourceAsStream("config.properties");
Properties props = new Properties();
props.load(ips);
ips.close();
String className = props.getProperty("className");
Collection collections = (Collection) Class.forName(className)
.newInstance();
ReflectPoint rp1 = new ReflectPoint(3, 5);
ReflectPoint rp2 = new ReflectPoint(3, 3);
ReflectPoint rp3 = new ReflectPoint(3, 8);
ReflectPoint rp4 = new ReflectPoint(3, 5);
collections.add(rp1);
collections.add(rp2);
collections.add(rp3);
collections.add(rp4);
collections.add(rp1);
System.out.println(collections.size());
}
}
public class ReflectPoint {
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;
}
public String toString() {
return str1 + "::" + str2 + "::" + str3;
}
@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;
ReflectPoint other = (ReflectPoint) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}