Reputation: 2594
Let's say I have two classes Animal and Food:
public class Animal {
String animalName = "";
Food animalFood;
public Animal(String animalName, Food food) {
this.animalFood = animalFood;
this.animalName = animalName;
}
}
public class Food {
String foodType;
String foodName;
public Food(String foodType, String foodName) {
this.foodName = foodName;
this.foodType = foodType;
}
}
public static void main(String[] args) {
Food dogFood = new Food("meat", "beef");
Animal animal = new Animal("Max", dogFood);
//problem: get animal from dogfood
}
Is there anyway, through Reflection or otherwise to get an instance of a class from its fields (assuming that you have access to the fields)?
Edit: The example obviously isn't the real problem, so lets say I only have the dogfood
instance which is created from an anynomous Instance of Animal
(animal
in this case) how do I get animal from it?
Upvotes: 0
Views: 374
Reputation: 35598
I think what you're trying to do is this:
Given
public class Animal {
String animalName = "";
Food animalFood;
public Animal(String animalName, Food food) {
this.animalFood = animalFood;
this.animalName = animalName;
}
}
And then something like
public static void main(String[] args) {
Food dogFood = new Food("meat", "beef");
doSomethingWithAnimal(new Animal("Max", dogFood)); // <-- anonymous creation of an Animal
//problem: get animal from dogfood
Animal theAnonymousAnimal = //get it via reflection from dogFood
}
No, this isn't possible. Food
does not contain a reference to Animal
therefore you cannot. If Food
had an Animal
field and in the Animal
constructor you set that reference, then yes, you could via normal reflection.
Upvotes: 1