سؤال

I am able to access a class and its variables, but is there anyway in changing a user defined variable?

e.g:

Class c = Class.forName(theclassname);
    Object o = c.newInstance();
    theclassname t = (theclassname) o;

i can do

t.variable = 1;

but can i do

String v = "variable";
t.v = 1;

in any way?

هل كانت مفيدة؟

المحلول

You can't use

Class c = Class.forName("C:\\A.txt");

on that way.

This piece of code returns Class by provided name, not the txt file.

Instead of this situation, you have to create class (suppose that is a class named A) and then retrieve Class A over reflection with following code:

Class c = Class.forName("A");

Note that is a class, not a txt file.

---EDIT---

With this edit you are completely changed the question.
Based on the new (edited) question, you can't use reflection as you wrote:

t.v = 1;

You should use this code:

t.getClass().getField(v).set(t, 1);

That will solve your problem.

نصائح أخرى

C:\A.txt is a text file ... a class file should end with .class !

Write a class A.java then compile it using

javac A.java

then you'll get A.class then you can load it using

Class c = Class.forName("A");

Note here that "A" is not the absolute or relative path to some file on the filesystem but the name of the resource for that class on the classpath. See the javadoc for Class#forName

You can use reflections to set a field like this

String v = "variable";
// like t.{v} = 1;
t.getClass().getField(v).set(t, 1);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top