private static Object createLoaderKey(String className, ClassLoader parentLoader,
                                          ProtectionDomain domain)
    {
        String packageName;
        {
            int index = className.lastIndexOf('.');
            if (index < 0) {
                packageName = "";
            } else {
                packageName = className.substring(0, index);
            }
        }

        // ProtectionDomain doesn't have an equals method, so break it apart
        // and add the elements to the composite key.

        Object domainKey = null;
        Object csKey = null;
        Object permsKey = null;
        Object principalsKey = null;

        if (domain != null) {
            domainKey = "";
            csKey = domain.getCodeSource();

            PermissionCollection pc = domain.getPermissions();
            if (pc != null) {
                List<Permission> permList = Collections.list(pc.elements());
                if (permList.size() == 1) {
                    permsKey = permList.get(0);
                } else if (permList.size() > 1) {
                    permsKey = new HashSet<Permission>(permList);
                }
            }

            Principal[] principals = domain.getPrincipals();
            if (principals != null && principals.length > 0) {
                if (principals.length == 1) {
                    principalsKey = principals[0];
                } else {
                    Set<Principal> principalSet = new HashSet<Principal>(principals.length);
                    for (Principal principal : principals) {
                        principalSet.add(principal);
                    }
                    principalsKey = principalSet;
                }
            }
        }

        return KeyFactory.createKey(new Object[] {
            parentLoader, packageName, domainKey, csKey, permsKey, principalsKey
        });
    }