ngreenwood6
ngreenwood6

Reputation: 8216

Java create dynamic class

I have 2 questions that I was hoping someone could help me with. Is there a way to create a class on the fly with android/java and also add variables to the class? For example I would like to do something like this:

Class c = new Class();
c.name = 'testing';
c.count = 0;

c.getName = new function(){
  return c.name;
}

Just wondering if this is possible or if there is another way to do this. Basically I want to build an object that I can use the data from as an object.

Upvotes: 1

Views: 2290

Answers (2)

Cheryl Simon
Cheryl Simon

Reputation: 46844

No, the syntax you describe is not possible in Java. I'm not sure what you are trying to accomplish there. If you want to create a class to use to hold data on the fly, you can create an anoynmous inner class.

Object object = new Object() {
  private String name = testing;
  private int count = 0;

  public String getName() {
    return name;
  }
}

In general, I wouldn't use this for a data objects though. This functionality is typically used for anonymous implementations of interfaces to support callbacks, etc.

Upvotes: 2

Bill K
Bill K

Reputation: 62769

This is not typically done. It can be done by reflection, but would be a fairly bad idea--This type of code is really annoying to debug, won't interact correctly in the IDE (For instance, ctrl-clicking on an instance of c.getName wouldn't be able to jump to where the method is defined), it would probably be a pretty big performance hit, etc.

However, for some generic tools this is possible. I believe Hibernate might have the ability to create classes from DB tables.

The most common use, however, is in mocking used within testing frameworks--They can do almost exactly what you want. Look at EasyMock with TestNG.

In general, though, you are better off just defining a business class and going with it rather than trying to make some abstract framework that generates your classes for you.

Upvotes: 1

Related Questions