vendredi 26 juillet 2019

How does reflection interact with static and instance classes?

I'm extremely new to Java, after a few hours of looking around I finally found a way to create new instances at runtime using Reflection. The issue being there is a certain amount of ambiguity in other answers and explanations of Reflection because people explain HOW to fix the problem and not WHY the fix works.

Currently the most broad reflection syntax I could find was:

Class clazz = Class.forName(fullClassPath);
Constructor<Color> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] {name});

But there are minor problems, I am having issues primarily with comprehension. In all other explanations the answers are hand-tailored to the error given. In my case while attempting to use it I apparently misunderstood the way it works.

public void createInstance() {
    String name = name; 
    try {
        Class clazz = Class.forName(fullClassPath);
        Constructor<Color> ctor = clazz.getConstructor(String.class);
        Object object = ctor.newInstance(new Object[] {name});
    } catch (Exception e) {
        }
    }

In my mind the way this would work is it would pull the current class, use it's constructor, and then rename the instance (also changing the directory name... I hope). The issue being there are some holes in that interpretation that I don't think fully mesh...

I should mention that this DOES throw an error and resorts to the catch statement rather than running the code.

I would expect reflection to require an instance method to run it properly so it can change the path for any class it is part of... but then an instance must be created PRIOR to calling the method, which would (in my mind) be unwieldy, and therefore probably incorrect.

In a static method it would have to pull from a common database, which would





Aucun commentaire:

Enregistrer un commentaire