Tuesday, 4 August 2009

Java reflection joy :)

Today I had to get database credentials to create connection manually. Of course in JBoss you are defining DataSource in default-ds.xml or in our case oracle-ds.xml which is then parsed by JBoss and you can get a Connection from JNDI (if its registered ;).

But if you have to create connection with the same credentials inside the EAR file which means you would have to specify username, password and db URL again the whole idea about keeping one information in one place fall apart and coding and deploying become to be huge pain and its error prone!

So... of course, the easiest way to get those credentials which are kept in private field called mcf in WrappedDataSource is to use reflection. mcf is a LocalManagedConnectionFactory (org.jboss.resource.adapter.jdbc.local) object which exposes all database configuration as properties. But if you think that you can write:

Field localManagedConnectionFactory = WrapperDataSource.class.getDeclaredField("mcf");


you are wrong ! ;)

Even if getDeclaredField method returns explicitly Field (java.lang.reflection) you still have to cast it to Field!!! So the final code looks like that:

Context ctx = new InitialContext();

DataSource ds = (DataSource) ctx.lookup("java:OracleDS");

Field localManagedConnectionFactory = (Field)WrapperDataSource.class.getDeclaredField("mcf");



localManagedConnectionFactory.setAccessible(true);

LocalManagedConnectionFactory mcf = (LocalManagedConnectionFactory )localManagedConnectionFactory.get(ds);

String database = mcf.getConnectionURL();


I can enjoy java over and over again ;)

No comments:

Post a Comment