I’ve written a few bluetooth apps now, but I had never seen this particular approach until recently. In the example they use device.getClass().getMethod("createRfcommSocket", new Class[] { int.class }); which seems to me a long way of just saying BluetoothSocket bs = createRfcommSocket(....
What is the difference between their approach
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
sock = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));
and mine
sock = createRfcommSocket(.....
Is there a reason to use one or the other?
Thank you
Yes, using getClass etc. is reflection.
The difference is that you get help from the IDE and the compiler in case you mistype the method name or make a similar mistake, while the authors of that code are on their own.
Maybe they are in a situation where the method to call just isn’t available at compile time, which might be the case in the context of software that allows loading in new plugins at runtime. But in that case you wouldn’t expect to see the method name and other details hardcoded into the code.
The literal text of your example just looks like poor programming to me.