Java OOP passing 'inner' field -


i'm playing object-oriented programming in java language , got idea i'm sure possible implement.

class class() {      int a,b,c;      ...       public void method(int x){...}      ...  } 

and possible pass name of variable located in class this:

obj.method(a); 

i know on 2 ways:
1. pass obj.a
2. pass kind of id , resolve id inmethod()

but i'm curious know possible pass name of variable?

better explanation: question possible pass string consist name of variable, , resolve in method , reference it?

you appear want pass name of parameter method , parameter. seem intent on not providing context of problem, leads me believe merely interested in possibility, , not looking use in actual application code. such, show sake of reference:

public void method(string parametername) {     try {         // can current field value:         int value = (int) getclass().getfield(parametername).get(this);          // , update (for example, set 23)         getclass().getfield(parametername).set(this, 23);     catch (nosuchfieldexception | illegalaccessexception ex) {         // field not exist or not public.     } } 

it can used follows (this sets value of field a 23 if exists).

myclass instance = new myclass(); instance.method("a"); 

note requires field public. possible non-public fields worse idea, since bypasses entire access control mechanism of java. there better solutions involve using map object implement similar kind of structure. these better using this.

last remark (i cannot stress enough): not use reflection calls in actual code! possible need without (for example, use map<string, integer> instead of individual fields).


Comments

Popular posts from this blog

android - Pass an Serializable object in AIDL -

How to provide Authorization & Authentication using Asp.net, C#? -

How to use Authorization & Authentication in Asp.net, C#? -