-1

My idea was to use casting to get a StringBuilder object to pass a valid argument to a method. Like this:

public TTTButton(String color) {
    StringBuilder sb = new StringBuilder();
    sb.append("Color."+ color.toString().toUpperCase());
    this.setBackground((Color)(Object)sb);// Runtime Exception: java.lang.StringBuilder cannot be cast to java.awt.Color 

Please share your thoughts on why such things are impossible (or maybe they are possible)?

7
  • 5
    Because a cast is not the same thing as an Eval function. Commented Jan 14, 2014 at 0:17
  • You can't cast it, because a String is not a Color. You can perform a lookup, as in my answer to your previous question. Commented Jan 14, 2014 at 0:19
  • A StringBuilder is not a Color. Casting only works if they actually are the right type. Commented Jan 14, 2014 at 0:19
  • Fyi, sb.append("a" + b) does sb.append(new StringBuilder("a").append(b).toString()) under the hood so your explicit StringBuilder is redundant. Commented Jan 14, 2014 at 0:19
  • @RobertHarvey, and if string arguments were automatically evaled as in the example, then System.out.println("new java.lang.String(\"foo\")"); would be ambiguous. Commented Jan 14, 2014 at 0:22

1 Answer 1

1

String or StringBuilder is not Color type so you can't use casting here. Maybe try to use Color.getColor(colorName) where colorName is String.

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

3 Comments

Note - where it is a String, not a StringBuilder...
As people explained before, you just cannot cast from String to Color because the interpreter won't know how to do such a conversion. For the sake of curiosity, a way to do what you want is like this import java.awt.Color; import bsh.EvalError; import bsh.Interpreter; public class ColorEval { public static void main(String[] args) throws EvalError { Interpreter bsh = new Interpreter(); bsh.eval("java.awt.Color c = java.awt.Color.BLACK"); Color black = (Color)bsh.eval("c"); System.out.println(black.equals(Color.BLACK)); } }
public TTTButton(String color) throws EvalError {Color passedColor = (Color)bsh.eval("Color."+ color.toString().toUpperCase()); this.setBackground(passedColor); Works fantastically! I think it allows to construct any method, argument or anything from string. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.