在A中定义两个返回uuu和iiii的方法,在B中调用A类中这个方法取得A中的变量值,这样可以满足你的要求吗?

解决方案 »

  1.   

    简单一点可以在A中也写一个getElement(String x)方法,然后在B中的getElement方法中直接转到A。麻烦一点可以用java的反射。
    http://java.sun.com/docs/books/tutorial/reflect/index.html
      

  2.   

    可以用Class类来实现,具体你参考javadoc就知道了。
      

  3.   

    谢谢上面两位,我从新说明我的意思,我的意思是我传的String x中的x是A中的属性的名称,比如我调用B中的getElement("uuu"),那么就返回A中的uuu属性的值,而且在A中我不想提供方法,他只存变量值!
      

  4.   

    说过用反射了呀!
    http://java.sun.com/docs/books/tutorial/reflect/index.html
      

  5.   

    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+"***");
    }
    }
      

  6.   

    to ccsxg (CHINA巴蒂) 
    以上代码你可以分别用
    java B uuu和java B iiii来测试
      

  7.   

    XIXI,其实这种典型的键-值,我都觉得没必要用反射。
    HashTable,Properties,ResourceBundle
    能替代的太多了!