Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

picking variable type from database  RSS feed

 
Nidhi Singhal
Ranch Hand
Posts: 89
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

In my application, I want to pick up the variable's type from the database and form a variable of that type.

For Ex.

private Controls.Custom.StatLogger DBLogger;
--------------------------

Here Controls.Custom.StatLogger is the type of variable DBLogger.
This type is stored in a database table. Once I pick this string from the database like
String str = "Controls.Custom.StatLogger";

the problem comes in constructing the varibale of that type:
private Controls.Custom.StatLogger DBLogger;

Can anyone help me out in this?

Thanks,
Nidhi
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use the Class.forName(...) method for that, and construct an instance by then calling ...newInstance() on it, provided it has a no-argument constructor.

The difficulty is in how to refer to that object in your code. I'd advise to come up with a common interface that all the dynamic objects created in this way implement, e.g. "StatLoggerI".

Then the code will look somewhat like this:

 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to add to what Ulf has mentioned.
1) If there is no zero-arg constructor, then you can also get the required constructor using different flavours of method getConstructors() in java.lang.Class.
2) If you have a setter method for this type of variable in the holder class, you can further use reflection to execute the setter with the newly constructed object.

I would strongly second the suggestion by Ulf that there should be a common interface for referring to such dynamic objects. However, you can very well live without it.
 
Nidhi Singhal
Ranch Hand
Posts: 89
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. This is great.
But, if I want to call a method in the obj (the class loaded using Class.forName),
say:
dbLogger.logStat();
I cannot do that at the compile time. The code wouldn't compile.
Is there any way of calling a method within that class?

Thanks,
Nidhi
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is why it was recommended that all the objects implement a common interface. The logStat() method should be a member of this interface.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!