1

I have a question, i have a code like below:

controller.start(c.class, 1);

but i want to set "c" from console. I can get/set it from args on main method . but how can i put it on c.class ? I mean how can i do that?

String a = "c";

controller.start(a.class,1);

Of course it doesnt work , but i hope i can tell u about my problem

On php we can use $$string to set/get string to variable, but i dont know how can we do it on Java ?

6
  • 3
    Look into Class.forName(..). Commented Mar 9, 2014 at 23:51
  • its not working ,thanks for quick reply Commented Mar 9, 2014 at 23:52
  • What does not working mean? Commented Mar 9, 2014 at 23:52
  • Class c = Class.forName(siteClass); controller.start(c, 1); its working , so thanks @SotiriosDelimanolis :)) Commented Mar 9, 2014 at 23:53
  • Class c = Class.forName(siteClass); c.parseData(page); method on c cant runnable ? how can i call parseData method on c ? Commented Mar 11, 2014 at 9:21

1 Answer 1

1

More commonly used (and more secure) way of addressing this is using maps:

private static final Map<String, Class<?>> NAME_TO_CLASS = new Map<>();
static {
  NAME_TO_CLASS.put("c", c.class);
  ...
}

static void main(String[] args) {
  ...
  controller.start(NAME_TO_CLASS.get(args[0]), 1);
}

Of course in real life you'd want to check if argument is correct and is in the map NAME_TO_CLASS.contains(your_arg);

Sign up to request clarification or add additional context in comments.

1 Comment

Class c = Class.forName(siteClass); c.parseData(page); method on c cant runnable ? how can i call parseData method on c ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.