-1

Is it possible in java to declare and instantiate a class at runtime?

I am attempting following code:

    public static void t4() {
    Object o = new Object() {
        private String uid = "1";
        private String name = "2";

        public String getName() {
            return name;
        }

        public String getUid() {
            return uid;
        }

        public void setName(String name) {
            this.name = name;
        }

        public void setUid(String uid) {
            this.uid = uid;
        }

        @Override
        public String toString() {
            return uid + " " + name;
        }
    };

But, I would want this to happen using reflection, cause i will be injecting attributes into pojo from xml source.

Any more thoughts?

gpa
  • 2,411
  • 6
  • 38
  • 68
  • Dive deep into [`Reflection API`](http://docs.oracle.com/javase/tutorial/reflect/index.html) – Rohit Jain Oct 16 '12 at 21:08
  • and [`ClassLoader`](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/ClassLoader.html) – John Dvorak Oct 16 '12 at 21:10
  • A bit of googling should turn up hundreds of pages on this... – DNA Oct 16 '12 at 22:19
  • possible duplicate of [What is difference between "Class.forName()" and "Class.forName().newInstance()"?](http://stackoverflow.com/questions/2092659/what-is-difference-between-class-forname-and-class-forname-newinstance) – DNA Oct 16 '12 at 22:20

2 Answers2

1

It is possible upto some degree to dynamically compile a class using the JDK6.0's Java Compiler API from a String object(holding the code).

http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm refer here.

The code also shows you how to dynamically instantiate that "newly compiled" class from a class file(using Class.forName()) method.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
1

Well there are answers all over the internet for this... here you go with one

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

The answer of above post demonstrates how to create a new instance on run time.

Community
  • 1
  • 1
Sap
  • 5,197
  • 8
  • 59
  • 101