0

Is there a way to pass the class type dynamically.

Please consider this:

cool_project.my_package;

class ImportClass {
    public void importClassMethod() {
        // Do Things
    }
}

Then:

class OtherClass {
    private String fullClassPath = "cool_project.my_package.ImportClass";

    private void otherClassMethod() {
        Class myClass = Class.forName(fullClassPath);
        Constructor constructor;
        try {
            constructor = myClass.getConstructor(Context.class);

            cool_project.my_package.ImportClass importClass = (cool_project.my_package.ImportClass) constructor.newInstance(mContext);
            importClass.importClassMethod();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}  

Is it possible to:

/* Get Type From fullClassPath */ importClass = (/* Get Type From fullClassPath */) constructor.newInstance(mContext);
Program-Me-Rev
  • 6,184
  • 18
  • 58
  • 142
  • Possible duplicate of [java: how can i do dynamic casting of a variable from one type to another?](https://stackoverflow.com/questions/2127318/java-how-can-i-do-dynamic-casting-of-a-variable-from-one-type-to-another) – Tibrogargan Feb 03 '18 at 01:44
  • 1
    If you will describe what you're actually trying to accomplish, you're likely to get more useful answers. – chrylis -cautiouslyoptimistic- Feb 03 '18 at 01:46

0 Answers0