Hi all, I\'m working on a project that implements a compiler for a madeup langua
ID: 3618356 • Letter: H
Question
Hi all,I'm working on a project that implements a compiler for a madeup language. In part of my code, there's a field which may be anArrayList, String, or int. Instead of making a separate class forthis field, I decided to declare it as an Object. I have a method,getValue(), which returns a string representation of this field. Icheck what class the field is using this code.
private Object value; // value is defined later
if (value.getClass() == (newArrayList<Object>()).getClass())
Thus, for this if statement, I have already checked that theObject, value, is an arraylist. My question is how can I nowaddress value as an arraylist. Even though I've confirmed what itis, I still can't call any ArrayList methods on value (e.g.value.add() or value.get() ).
In brief, how can I convert value from Object to ArrayList (orString or int) once I've confirmed what its class is?
I'm working on a project that implements a compiler for a madeup language. In part of my code, there's a field which may be anArrayList, String, or int. Instead of making a separate class forthis field, I decided to declare it as an Object. I have a method,getValue(), which returns a string representation of this field. Icheck what class the field is using this code.
private Object value; // value is defined later
if (value.getClass() == (newArrayList<Object>()).getClass())
Thus, for this if statement, I have already checked that theObject, value, is an arraylist. My question is how can I nowaddress value as an arraylist. Even though I've confirmed what itis, I still can't call any ArrayList methods on value (e.g.value.add() or value.get() ).
In brief, how can I convert value from Object to ArrayList (orString or int) once I've confirmed what its class is?
Explanation / Answer
if (value.getClass() == (newArrayList<Object>()).getClass()) { ArrayList<Object> myList = (ArrayList<Object>)value; } else if (value.getClass() == String.class) { String myString = (String) value; } etc. etc.
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.