intersect
intersect

Reputation: 3

Passing arguments java8

I have a method doStuff(String arg1). I invoke it from the object someObject, passing it the "constant name" as the String argument. Can I get the value of this variable inside the doStuff method?

public Class1 {
     someObject.doStuff("SOME_CONST");
}


public Class2 {
     public static final String SOME_CONST = "someString";

     public void doStuff(String arg1) {
          doMoreStuff(arg1); 
     }

     // expected: doMoreStuff("someString"), but actual:  
     doMoreStuff("SOME_CONST").
}

Upvotes: 0

Views: 57

Answers (3)

Jockie
Jockie

Reputation: 47

Not completely sure what you're asking but you can get the value by reflection, like this. (It will print CONSTANT)

public static class Class1 {
    public static void main(String[] args) {
        new Class2().doStuff("SOME_CONST");
    }
}

public static class Class2 {
    public static final String SOME_CONST = "CONSTANT";

    public void doStuff(String const_name) {
        try {
            String const_value = (String) Class2.class.getDeclaredField(const_name).get(null);
            System.out.println(const_value);
        }catch(NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 1

Nidhi257
Nidhi257

Reputation: 977

try this : someObject.doStuff(Class2.SOME_CONST); instead of someObject.doStuff("SOME_CONST");

Upvotes: 1

azro
azro

Reputation: 54168

If you want to pass the attribute : SOME_CONST

public static final String SOME_CONST = "someString";

As a parameter for : doMoreStuff(...) You need to write this : doMoreStuff(SOME_CONST);

Because doMoreStuff("SOME_COST"); will pass as parameter the String "SOME_COST" and not the variable

Upvotes: 0

Related Questions