0

I started to use Java Reflection recently but currently stuck at this.

So I have something like this:

Class<?> dogClass = Class.forName("com.example.dog");
Object dogObject = dogClass.newInstance();

I would like to use the above object in this arraylist:

List<Dog> dogList = new ArrayList();

So in normal case:

for(Dog d : dogList) {
....
.... 
}

But when I tried to use the java reflection, it doesn't work..

for(dogObject d : dogList) {
....
.... 
}

Can anyone enlighten me please? Thank you.

2
  • Use like this. for(Object d : dogList){ } Commented Sep 18, 2018 at 7:24
  • The for loop iterates over the objects already existing in the list. Where is the relationship to the new object you’ve just created? What do you want to achieve? Commented Sep 19, 2018 at 6:50

2 Answers 2

2

for(dogObject d : dogList) is wrong. dogObject is an object and not a type. add your dogObject to dogList and then loop it like you do in the first loop:

Class<?> dogClass = Class.forName("com.example.Dog");
Dog dogObject = (Dog)dogClass.newInstance();
List<Dog> dogList = new ArrayList<Dog>();
dogList.add(dogObject);
for (Dog dog : dogList) {
   ....         
}

(and you need to add try/catch of course)

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

Comments

0

Syntax of foreach loop is like below

for(T Obj: Objects) {
....
.... 
}

but in your code you are using Obj in-place of T (Object Type). It's wrong way of coding for each loop. in your code dogObject is instance of reflection class dogClass so java will throw compile error.

Comments

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.