A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 黎健东 中级黑马   /  2012-8-29 21:04  /  3801 人查看  /  5 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 黎健东 于 2012-8-29 21:10 编辑
  1. package com.lee.calc.test010;


  2. public class CopyOfBug4Visit {
  3.    
  4.     public static void main(String[] args) {
  5.         T t = new T();
  6.         t.getS1Name();
  7.         t.getS2Name();
  8.         

  9.     }

  10. }

  11. class T{
  12.     String s1;
  13.     String s2;
  14.     String s3;
  15.     String s4;
  16.     public T() {
  17.     }
  18.    
  19.     void getS1Name(){
  20.         method(s1);
  21.     }
  22.    
  23.     void getS2Name(){
  24.         method(s2);
  25.     }
  26.    
  27.     void method(String s){
  28.         //获取传入参数的变量名,并打印出来
  29.         System.out.println();
  30.     }
  31. }
复制代码
希望输出的结果是变量名
s1
s2

如何实现呢?
c#有获得变量名的方法,java的有木有呢?

有童鞋可能会想到反射,不过这里的需求是,只想通过上面的方法拿到传入的s1 和s2,反射可以得到所有的变量名,但这里不需要所有的,只需要s1 s2

5 个回复

倒序浏览
本帖最后由 唐志兵 于 2012-8-29 21:33 编辑

得不到的。
回复 使用道具 举报
import java.lang.reflect.Field
public class Test3 {
   
    public static void main(String[] args) throws Exception {
        T t = new T();
        t.getS1Name();
        t.getS2Name();
        

    }

}

class T{
    String s1;
    String s2;
    public T() {
    }
   
    void getS1Name() throws Exception{
        method(s1);
    }
   
    void getS2Name() throws Exception{
        method(s2);
    }
            //获取传入参数的变量名,并打印出来
        
    void method(String s) throws Exception, Exception{
       Field[] fields = s.getClass().getFields();
    for(Field field : fields){
            if(field.getType() == String.class){
                    String oldValue = (String)field.get(s);
                    System.out.println(oldValue);
            }
           
    }
   
    }
}
回复 使用道具 举报
import java.lang.reflect.Field
public class Test3 {
   
    public static void main(String[] args) throws Exception {
        T t = new T();
        t.getS1Name();
        t.getS2Name();
        

    }

}

class T{
    String s1;
    String s2;
    public T() {
    }
   
    void getS1Name() throws Exception{
        method(s1);
    }
   
    void getS2Name() throws Exception{
        method(s2);
    }
            //获取传入参数的变量名,并打印出来
        
    void method(String s) throws Exception, Exception{
       Field[] fields = s.getClass().getFields();
    for(Field field : fields){
            if(field.getType() == String.class){
                    String oldValue = (String)field.get(s);
                    System.out.println(oldValue);
            }
           
    }
   
    }
}
回复 使用道具 举报
曹昌 发表于 2012-8-29 21:37
import java.lang.reflect.Field
public class Test3 {
   

楼上拿到的是所有String的变量名吗?而且代码不能执行?
回复 使用道具 举报
http://topic.csdn.net/u/20120523/16/9f2ecd60-28f8-4476-9d5a-916113f75131.html?r=78655575
C#的方法
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马