Java: How can I access a class's field by a name stored in a variable? -


How do I set or get a field in the name whose name is dynamic and stored in the string variable?

  Testing the public class {public string A1; Public string A2; Public Test (string key) {this.key = 'found'; & Lt; --- error}}  

You must use reflection:

  • Use to get references if it is not public, you will need to call instead
  • Use this to access the field if it is not public
  • To set the value, or if one of the similarly-named methods is a primitive

This is an example that is a public Is related to simple case of that area. If possible it would be a good option to use the properties.

  import java.lang.reflect.Field; Class Databies {// I do not like the public sector; It is * only * to make public string foo easy to display; } Public class test {public static zero main (string [] args) // One method throws exceptions / declaration / Similar is usually a bad idea; / Careful exceptions to cases of different failures {Field field = Data object Consider throwing the class .getField ("foo"); Data object o = new data object (); Field.set (o, "new value"); Println (o.foo); }}  

Comments

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -