Category Archives: java

Get packages from IProject in eclipse using IJavaProject

When working with Eclipse and especially when developing plug-ins you will deal with the org.eclipse.core.resources.IProject interface.

This however does not give you an option to get the packages used in the project. For that you will need org.eclipse.jdt.core.IJavaProject interface which is a completely different interface and cannot just get it from a cast from IProject, however you can:

IProject proj = (IProject)selectionResult;

IJavaProject jProj = JavaCore.create(proj);

then of course you can use jProj.getPackageFragments() to get app the package elements in the project.

You can also check if project is actually java project before creating the IJavaProject:

if(JavaProject.hasJavaNature(proj)) ...

 

 

Java reflection snippets

get class from name:

Class c = Class.forName("my.own.class");

Examples

        //no paramater
	Class noparams[] = {};

	//String parameter
	Class[] paramString = new Class[1];	
	paramString[0] = String.class;

	//int parameter
	Class[] paramInt = new Class[1];	
	paramInt[0] = Integer.TYPE;

	try{
	        //get glass
		Class c = Class.forName("my.own.class");
                //get instance of a class
		Object obj = cls.newInstance();
                //get nested class
                Class cnested = Class.forName("my.own.class$myInnerClass");
                //get all nested classes
                Class[] nested = c.getDeclaredClasses();

                //call private method. could return "my.own.class" instance for singletons
                Method m = c.getDeclaredMethod("getInstance", noparams); 
                m.setAccessible(true);
                obj = m.invoke(null, null);
		//call method, no params
		Method m = c.getDeclaredMethod("myMethod", noparams);
		m.setAccessible(true);
                m.invoke(obj, null);

		//call method, pass String param 
		m = c.getDeclaredMethod("stringMethod", paramString);
                m.setAccessible(true);
		m.invoke(obj, new String("input data"));

		//call method, pass int param
		m = c.getDeclaredMethod("intMethod", paramInt);
                m.setAccessible(true);
		m.invoke(obj, 123456);

                //get field
                Field f = getDeclaredField("myVar");
                f.setAccessible(true);
                //get its value
                Object val = f.get(obj);
	}catch(Exception ex){
		ex.printStackTrace();
	}

 

 

 

links:

http://docs.oracle.com/javase/tutorial/reflect/

http://docs.oracle.com/javase/tutorial/reflect/class/classNew.html

http://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html

zipOutputStream.closeEntry() : invalid entry compressed size

have you hit an exception like this:

java.util.zip.ZipException: invalid entry compressed size (expected 960092 but got 962733 bytes)

?

Well, this is because ZipOutputStream tries to close a ZipEntry with a different size than its size property. This is because:

zipOutputStream.putNextEntry(inEntry);

OR

zipOutputStream.putNextEntry(new ZipEntry(inEntry));

Creating new ZipEntry like this resulting in copying all the properties of the old one. However the resulting zipped size can differ so if you don’t care about preserving other fields than name this constructor can be used:

zipOutputStream.putNextEntry(new ZipEntry(inEntry.getName()));

 

Why c++ is not pure object oriented language?

I have just been asked why c++ is not pure object oriented language.

Well the answer is simple: – C++ supports object-oriented programming, but OO is not intrinsic to the language. In c++ you can write a valid, well-coded, excellently-styled C++ program without using a single object, while in Java or c# you cannot write anything without using classes and objects. For example:

class HelloWorld  {
public static void main(String[] args) {
System.out.println("Hello World!"); 
}
}

and c++

int main ()
{
cout << "Hello World!";
return 0;
}

There a good article related to OOPSLA: http://www.stroustrup.com/oopsla.pdf

 

java byte array related snippets

byte[] int2toByteArray(int value) {
     return  ByteBuffer.allocate(4).putInt(value).array();
}

byte[] int2toByteArray_(int value) {
    return new byte[] {
        (byte) (value >> 24),
        (byte) (value >> 16),
        (byte) (value >> 8),
        (byte) value};
}

int byteArray2Int(byte[] bytes) {
     return ByteBuffer.wrap(bytes).getInt();
//you can use specify the expected byte order
//ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt();
}

int byteArray2Int_(byte[] bytes) {
     return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF)
}

Bluetooth UUID – how to find it

So you have tried to connect to your Arduino using some BT modem from your Android device ? … and you couldn’t … well you probably used a wrong UUID here:
createRfcommSocketToServiceRecord(UUID.fromString(“fa87c0d0-afac-11de-8a39-0800200c9a66”))

For this case you should simple use this one: “00001101-0000-1000-8000-00805F9B34FB”

So how do you know this? From this table:

BASE_UUID 00000000-0000-1000-8000-00805F9B34FB
Service Class Name UUID Specification Allowed Usage
ServiceDiscoveryServerServiceClassID 0x1000 Bluetooth Core Specification Service Class
BrowseGroupDescriptorServiceClassID 0x1001 Bluetooth Core Specification Service Class
SerialPort 0x1101 Serial Port Profile (SPP)
NOTE: The example SDP record in SPP v1.0 does not include a BluetoothProfileDescriptorList attribute, but some implementations may also use this UUID for the Profile Identifier.
Service Class/ Profile
LANAccessUsingPPP 0x1102 LAN Access Profile
[DEPRECATED]
NOTE: Used as both Service Class Identifier and Profile Identifier.
Service Class/ Profile
DialupNetworking 0x1103 Dial-up Networking Profile (DUN)
NOTE: Used as both Service Class Identifier and Profile Identifier.
Service Class/ Profile
IrMCSync 0x1104 Synchronization Profile (SYNC)
NOTE: Used as both Service Class Identifier and Profile Identifier.
Service Class/ Profile
OBEXObjectPush 0x1105 Object Push Profile (OPP)
NOTE: Used as both Service Class Identifier and Profile.
Service Class/ Profile
OBEXFileTransfer 0x1106 File Transfer Profile (FTP)
NOTE: Used as both Service Class Identifier and Profile Identifier.
Service Class/ Profile
IrMCSyncCommand 0x1107 Synchronization Profile (SYNC)
Headset 0x1108 Headset Profile (HSP)
NOTE: Used as both Service Class Identifier and Profile Identifier.
Service Class/ Profile
CordlessTelephony 0x1109 Cordless Telephony Profile (CTP)
NOTE: Used as both Service Class Identifier and Profile Identifier.
[DEPRECATED]
Service Class/ Profile
AudioSource 0x110A Advanced Audio Distribution Profile (A2DP) Service Class
AudioSink 0x110B Advanced Audio Distribution Profile (A2DP) Service Class
A/V_RemoteControlTarget 0x110C Audio/Video Remote Control Profile (AVRCP) Service Class
AdvancedAudioDistribution 0x110D Advanced Audio Distribution Profile (A2DP) Profile
A/V_RemoteControl 0x110E Audio/Video Remote Control Profile (AVRCP)
NOTE: Used as both Service Class Identifier and Profile Identifier.
Service Class/ Profile
A/V_RemoteControlController 0x110F Audio/Video Remote Control Profile (AVRCP)
NOTE: The AVRCP specification v1.3 and later require that 0x110E also be included in the ServiceClassIDList before 0x110F for backwards compatibility.
Service Class
Intercom 0x1110 Intercom Profile (ICP)
NOTE: Used as both Service Class Identifier and Profile Identifier.
[DEPRECATED]
Service Class
Fax 0x1111 Fax Profile (FAX)
NOTE: Used as both Service Class Identifier and Profile Identifier.
[DEPRECATED]
Service Class
Headset – Audio Gateway (AG) 0x1112 Headset Profile (HSP) Service Class
WAP 0x1113 Interoperability Requirements for Bluetooth technology as a WAP, Bluetooth SIG [DEPRECATED] Service Class
WAP_CLIENT 0x1114 Interoperability Requirements for Bluetooth technology as a WAP, Bluetooth SIG [DEPRECATED] Service Class
PANU 0x1115 Personal Area Networking Profile (PAN)
NOTE: Used as both Service Class Identifier and Profile Identifier for PANU role.
Service Class / Profile
NAP 0x1116 Personal Area Networking Profile (PAN)
NOTE: Used as both Service Class Identifier and Profile Identifier for NAP role.
Service Class / Profile
GN 0x1117 Personal Area Networking Profile (PAN)
NOTE: Used as both Service Class Identifier and Profile Identifier for GN role.
Service Class / Profile
DirectPrinting 0x1118 Basic Printing Profile (BPP) Service Class
ReferencePrinting 0x1119 See Basic Printing Profile (BPP) Service Class
Basic Imaging Profile 0x111A Basic Imaging Profile (BIP) Profile
ImagingResponder 0x111B Basic Imaging Profile (BIP) Service Class
ImagingAutomaticArchive 0x111C Basic Imaging Profile (BIP) Service Class
ImagingReferencedObjects 0x111D Basic Imaging Profile (BIP) Service Class
Handsfree 0x111E Hands-Free Profile (HFP)
NOTE: Used as both Service Class Identifier and Profile Identifier.
Service Class / Profile
HandsfreeAudioGateway 0x111F Hands-free Profile (HFP) Service Class
DirectPrintingReferenceObjectsService 0x1120 Basic Printing Profile (BPP) Service Class
ReflectedUI 0x1121 Basic Printing Profile (BPP) Service Class
BasicPrinting 0x1122 Basic Printing Profile (BPP) Profile
PrintingStatus 0x1123 Basic Printing Profile (BPP) Service Class
HumanInterfaceDeviceService 0x1124 Human Interface Device (HID)
NOTE: Used as both Service Class Identifier and Profile Identifier.
Service Class / Profile
HardcopyCableReplacement 0x1125 Hardcopy Cable Replacement Profile (HCRP) Profile
HCR_Print 0x1126 Hardcopy Cable Replacement Profile (HCRP) Service Class
HCR_Scan 0x1127 Hardcopy Cable Replacement Profile (HCRP) Service Class
Common_ISDN_Access 0x1128 Common ISDN Access Profile (CIP)
NOTE: Used as both Service Class Identifier and Profile Identifier.
[DEPRECATED]
Service Class / Profile
SIM_Access 0x112D SIM Access Profile (SAP)
NOTE: Used as both Service Class Identifier and Profile Identifier.
Service Class / Profile
Phonebook Access – PCE 0x112E Phonebook Access Profile (PBAP) Service Class
Phonebook Access – PSE 0x112F Phonebook Access Profile (PBAP) Service Class
Phonebook Access 0x1130 Phonebook Access Profile (PBAP) Profile
Headset – HS 0x1131 Headset Profile (HSP)
NOTE: See erratum #3507.
0x1108 and 0x1203 should also be included in the ServiceClassIDList before 0x1131 for backwards compatibility.
Service Class
Message Access Server 0x1132 Message Access Profile (MAP) Service Class
Message Notification Server 0x1133 Message Access Profile (MAP) Service Class
Message Access Profile 0x1134 Message Access Profile (MAP) Profile
GNSS 0x1135 Global Navigation Satellite System Profile (GNSS) Profile
GNSS_Server 0x1136 Global Navigation Satellite System Profile (GNSS) Service Class
PnPInformation 0x1200 Device Identification (DID)
NOTE: Used as both Service Class Identifier and Profile Identifier.
Service Class / Profile
GenericNetworking 0x1201 N/A Service Class
GenericFileTransfer 0x1202 N/A Service Class
GenericAudio 0x1203 N/A Service Class
GenericTelephony 0x1204 N/A Service Class
UPNP_Service 0x1205 Enhanced Service Discovery Profile (ESDP) [DEPRECATED] Service Class
UPNP_IP_Service 0x1206 Enhanced Service Discovery Profile (ESDP) [DEPRECATED] Service Class
ESDP_UPNP_IP_PAN 0x1300 Enhanced Service Discovery Profile (ESDP) [DEPRECATED] Service Class
ESDP_UPNP_IP_LAP 0x1301 Enhanced Service Discovery Profile (ESDP)[DEPRECATED] Service Class
ESDP_UPNP_L2CAP 0x1302 Enhanced Service Discovery Profile (ESDP)[DEPRECATED] Service Class
VideoSource 0x1303 Video Distribution Profile (VDP) Service Class
VideoSink 0x1304 Video Distribution Profile (VDP) Service Class
VideoDistribution 0x1305 Video Distribution Profile (VDP) Service Class
HDP 0x1400 Health Device Profile Profile
HDP Source 0x1401 Health Device Profile (HDP) Service Class
HDP Sink 0x1402 Health Device Profile (HDP) Service Class
(Max value 0xFFFF)

More info can be found here: https://www.bluetooth.org/en-us/specification/assigned-numbers-overview/service-discovery

Enjoy 🙂

java overriding static method

Can we override a static method? – Yes, WE CAN! 🙂 but we don;t get the same effect as with non-static ones.

Static methods are not associated with an instance of a class. thus you cannot really override them, but:

class Main {
    public static void main(String args[]) {
            SuperClass a = new SubClass();
            SubClass b = new SubClass ();
            a.imStatic();
            b.imStatic();
            a.callStatic();
            b.callStatic();
    }
}
abstract class SuperClass {
    public static void imStatic() {
        System.out.println("I am superclass");
    }

    public void callStatic() {
        imStatic(); //no late binding here; always calls A.foo()
    }
}

class SubClass extends SuperClass {
    public static void imStatic() {
        System.out.println("I am subclass");
    }
}

the we get:

I am superclass
I am subclass
I am superclass
I am superclass

So what really matter is the type of the caller class, not the instance.