黑马程序员技术交流社区
标题:
一个字符编码和反射的问题
[打印本页]
作者:
许鑫星
时间:
2013-3-12 16:07
标题:
一个字符编码和反射的问题
本帖最后由 许鑫星 于 2013-3-12 20:10 编辑
复制代码
public class Classloader {
public static void main(String[] args) {
try {
Classloader cl = new Classloader();
HttpURLConnection conn = (HttpURLConnection) cl.invoke(new URL("http://www.itheima.com"), "openConnection");
//不知道为什么不能这不写,提示是can not access a member of class sun.net.www.protocol.http.HttpURLConnection$HttpInputStream with modifiers "public"
//InputStream is = (InputStream)cl.invoke(conn, "getInputStream");
BufferedInputStream is = new BufferedInputStream((InputStream)cl.invoke(conn, "getInputStream"));
byte[] b = new byte[1024];
int len;
while((len = (Integer) cl.invoke(is, "read",b))!=-1){
//这里虽然能显示出来大部分的中文,但是也会有一些??出现,为什么呢?
System.out.println(new String(new String(b,0,len).getBytes(),"utf-8"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Object invoke(Object clazz,String method,Object...objs) throws Exception{
Class cls = clazz.getClass();
Class[] clsx = new Class[objs.length];
for(int i = 0;i<objs.length;i++) {
clsx[i] = objs[i].getClass();
}
Method me = cls.getMethod(method,clsx);
return me.invoke(clazz, objs);
}
}
复制代码
今天刚看了反射,写了个小程序,上面这段程序我想用我自己写的反射方法来调用,但是结果得到的数据有一点点的乱码,我想问一下是什么造成的,另外反射调用的时候对于方法参数是基本类型的由于不能用Object来接收,所以调用不了,有没有什么好的方法来解决呢?
作者:
谢洋
时间:
2013-3-12 20:04
public static void main(String[] args) {
try {
Classloader cl = new Classloader();//你这是类加载器ClassLoader么?,还是你自定义的?
HttpURLConnection conn = (HttpURLConnection) cl.invoke(new URL("http://www.itheima.com"), "openConnection");
//不知道为什么不能这不写,提示是can not access a member of class sun.net.www.protocol.http.HttpURLConnection$HttpInputStream with modifiers "public"
//InputStream is = (InputStream)cl.invoke(conn, "getInputStream");
Classloader,那来这么一个方法,没有把Classloader代码贴出来怎么看?
BufferedInputStream is = new BufferedInputStream((InputStream)cl.invoke(conn, "getInputStream"));
byte[] b = new byte[1024];
int len;
while((len = (Integer) cl.invoke(is, "read",b))!=-1){
//这里虽然能显示出来大部分的中文,但是也会有一些??出现,为什么呢?
System.out.println(new String(new String(b,0,len).getBytes(),"utf-8"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Object invoke(Object clazz,String method,Object...objs) throws Exception{//这个好像与上面调用的无关?代码不全
Class cls = clazz.getClass();
Class[] clsx = new Class[objs.length];
for(int i = 0;i<objs.length;i++) {
clsx
= objs
.getClass();
}
Method me = cls.getMethod(method,clsx);
return me.invoke(clazz, objs);
}
请问你代表码全贴出来了么?
下面没注释的通过了?
作者:
许鑫星
时间:
2013-3-12 20:09
谢洋 发表于 2013-3-12 20:04
public static void main(String[] args) {
try {
Classloader c ...
呃。。这不是类加载器,那个是ClassLoader,是我自定义的一个类Classloader,整个代码不全,放到类Classloader里就行了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2