0

I have List of objects and need to type cast from class name. e.g

public void foo(List configs){
    //configs type cast code
    configs.forEach(config -> {
        String value = config.getValue();
    });
}

Is there any way to do this?

2
  • Which part of the code is "type cast"? Commented Apr 4, 2018 at 10:08
  • You need a List<SomeClassWithGetValueMethod> to make it work. You need to see how generic works. Commented Apr 4, 2018 at 10:15

1 Answer 1

1

Use a generic type : List<Config>.
The compiler handles the generic of raw Collections as Object. So it is like if you had declared : List<Object>.

Supposing you have a List of Config instances, you could write :

public void foo(List<Config> configs){
    configs.forEach(config -> {
                String value = config.getValue();
                // use the value ...
              });    
}
Sign up to request clarification or add additional context in comments.

2 Comments

but it gives me error "The method getValue() is undefined for the type Object" in for loop. thats why I mentioned for loop specifically.
@ Joop Eggen Right. I added it.

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.