求救!高分!关于JAVA类调用的问题100分,在线等待 在A中定义两个返回uuu和iiii的方法,在B中调用A类中这个方法取得A中的变量值,这样可以满足你的要求吗? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 简单一点可以在A中也写一个getElement(String x)方法,然后在B中的getElement方法中直接转到A。麻烦一点可以用java的反射。http://java.sun.com/docs/books/tutorial/reflect/index.html 可以用Class类来实现,具体你参考javadoc就知道了。 谢谢上面两位,我从新说明我的意思,我的意思是我传的String x中的x是A中的属性的名称,比如我调用B中的getElement("uuu"),那么就返回A中的uuu属性的值,而且在A中我不想提供方法,他只存变量值! 说过用反射了呀!http://java.sun.com/docs/books/tutorial/reflect/index.html public class A{ public static String uuu="hello"; public static String iiii="world";}——————————————————————————————import java.lang.reflect.*;public class B{ public String getElement(String x) { A a=new A(); Field field=null; try { field=a.getClass().getField(x); } catch(NoSuchFieldException e) { System.err.println("no such field"); e.printStackTrace(); } catch(SecurityException e) { System.err.println("security exception"); e.printStackTrace(); } if(field==null) return "no such field"; Object obj=null; try { obj=field.get(a); }catch(Exception e){e.printStackTrace();} String value=(String)obj; return value; } public static void main(String[] args) { if(args.length==0) { System.out.println("please input an arg"); System.exit(0); } String key=args[0]; B b=new B(); String s=b.getElement(key); System.out.println("***"+s+"***"); }} to ccsxg (CHINA巴蒂) 以上代码你可以分别用java B uuu和java B iiii来测试 XIXI,其实这种典型的键-值,我都觉得没必要用反射。HashTable,Properties,ResourceBundle能替代的太多了! WEB服务器里的数据库连接池不够用了怎么办? 你愿意去那个公司(疯狂散分中)? 帮忙解释一句话?谢谢 ServerSocket有关问题 java.lang.ArrayIndexOutOfBoundsException: 1错误 几道作业题目据说是剑桥大学研究生一年级的作业 一个初步想法,共同开发JAVA开放源码的远程控制软件. JAVA小程序中的setBackground(Color c) 请教有关jdk库的文档的问题 使用jgoodies改变JAVA桌面程序的观感 怎样解决java应用程序在linux下无法显示汉字问题 如何取得新邮件?
http://java.sun.com/docs/books/tutorial/reflect/index.html
http://java.sun.com/docs/books/tutorial/reflect/index.html
{
public static String uuu="hello";
public static String iiii="world";}
——————————————————————————————
import java.lang.reflect.*;
public class B
{
public String getElement(String x)
{
A a=new A();
Field field=null;
try
{
field=a.getClass().getField(x);
}
catch(NoSuchFieldException e)
{
System.err.println("no such field");
e.printStackTrace();
}
catch(SecurityException e)
{
System.err.println("security exception");
e.printStackTrace();
}
if(field==null)
return "no such field";
Object obj=null;
try
{
obj=field.get(a);
}catch(Exception e){e.printStackTrace();}
String value=(String)obj;
return value;
}
public static void main(String[] args)
{
if(args.length==0)
{
System.out.println("please input an arg");
System.exit(0);
}
String key=args[0];
B b=new B();
String s=b.getElement(key);
System.out.println("***"+s+"***");
}
}
以上代码你可以分别用
java B uuu和java B iiii来测试
HashTable,Properties,ResourceBundle
能替代的太多了!