Is there any way to initialize variables from object and class names?(such as by using reflections)

For example: let us say there is a class Dog , a subclass Dalmatian and the Dog class has private variables String name, breed; Now I say in main:

Dog spot = new Dalamatian();

and automatically it get name = "spot" and breed = "Dalmatian".

Jon Skeet
people
quotationmark

It's easy to get the breed:

public class Dog {
    private final String name;
    private final String breed;

    protected Dog(String name) {
        // Default to using the class name
        this(name, getClass().getSimpleName());
    }

    protected Dog(String name, String breed) {
        // Allow subclasses to specify an explicit breed
        this.name = name;
        this.breed = breed;
    }
}

I don't believe there's any way of inferring spot though in Java. (You can do it in C#, assuming this is a field rather than a local variable, using CallerMemberName...)

So basically you'd need

Dog spot = new Dalmation("spot");

people

See more on this question at Stackoverflow