java 字符串转为变量名 变量名转为字符串 (局部变量无效)

 

import java.lang.reflect.Field;

public class Main {

    public static void main(String[] args) {
        String varName = "myVariable";
        
        try {
            // 获取类的字段
            Field field = MyClass.class.getDeclaredField(varName);
            field.setAccessible(true);
            
            // 创建对象并赋值给变量
            MyClass obj = new MyClass();
            field.set(obj, "Hello, World!");
            
            // 输出变量的值
            System.out.println(obj.myVariable);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

class MyClass {
    private String myVariable;
}

import java.lang.reflect.Field;

public class Main {

    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.myVariable = "Hello, World!";
        
        // 直接使用变量名作为字符串
        String varName1 = "myVariable";
        System.out.println(varName1);  // 输出: myVariable
        
        try {
            // 使用反射机制获取变量名称
            Field field = MyClass.class.getDeclaredField(varName1);
            String varName2 = field.getName();
            System.out.println(varName2);  // 输出: myVariable
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

class MyClass {
    public String myVariable;
}

 

你可能感兴趣的:(java,开发语言)