黑马程序员技术交流社区
标题:
如何获取一个传入参数的变量名
[打印本页]
作者:
黎健东
时间:
2012-8-29 21:04
标题:
如何获取一个传入参数的变量名
本帖最后由 黎健东 于 2012-8-29 21:10 编辑
package com.lee.calc.test010;
public class CopyOfBug4Visit {
public static void main(String[] args) {
T t = new T();
t.getS1Name();
t.getS2Name();
}
}
class T{
String s1;
String s2;
String s3;
String s4;
public T() {
}
void getS1Name(){
method(s1);
}
void getS2Name(){
method(s2);
}
void method(String s){
//获取传入参数的变量名,并打印出来
System.out.println();
}
}
复制代码
希望输出的结果是变量名
s1
s2
如何实现呢?
c#有获得变量名的方法,java的有木有呢?
有童鞋可能会想到反射,不过这里的需求是,只想通过上面的方法拿到传入的s1 和s2,反射可以得到所有的变量名,但这里不需要所有的,只需要s1 s2
作者:
唐志兵
时间:
2012-8-29 21:30
本帖最后由 唐志兵 于 2012-8-29 21:33 编辑
得不到的。
作者:
曹操
时间:
2012-8-29 21:37
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 {
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:49
曹昌 发表于 2012-8-29 21:37
import java.lang.reflect.Field
public class Test3 {
楼上拿到的是所有String的变量名吗?而且代码不能执行?
作者:
黎健东
时间:
2012-8-29 21:50
http://topic.csdn.net/u/20120523/16/9f2ecd60-28f8-4476-9d5a-916113f75131.html?r=78655575
C#的方法
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2