0

I want to convert Attributes to String so that I can trim and get a substring of the attribute value.

Here is my code:

Attribute attrs = match.getAttributes();

NamingEnumeration e = attrs.getAll();
System.out.println(attrs.get("cn"));
System.out.print(attrs.get("uniqueMember"));

unique_members[i] = attrs.get("uniqueMember");

I am facing an error in the last line where I want to store the value of uniqueMember to the unique_members array. Error:

Type mismatch: cannot convert from Attribute to String

I have tried the following so far:

unique_members[i] = (String)attrs.get("uniqueMember");

It doesn't solve the issue and I am getting error:

Cannot cast attribute to String.

Jens
  • 67,715
  • 15
  • 98
  • 113
Maninder Singh
  • 135
  • 4
  • 12

4 Answers4

3

Use unique_members[i] = attrs.get("uniqueMember").toString() to convert the attribute value to a string.

For more informationens see the javadoc of BasicAttribute or javax.naming.directory.Attribute

Jens
  • 67,715
  • 15
  • 98
  • 113
1

Have a look at the Javadoc of Attributes class. You can use getValue(String) to retrieve the value of a specific attribute.

schrieveslaach
  • 1,689
  • 1
  • 15
  • 32
  • By using `getValue(String)` you do not need to cast or convert to `String` because the return type is already `String`. – schrieveslaach Aug 20 '15 at 13:49
  • 1
    You refering to a wron class because of a type in OP's question. attr is an istance of `javax.naming.directory.Attribute` not of `java.util.jar.Attributes` – Jens Aug 20 '15 at 18:38
1

I suggest to use null-safe Objects.toString() for getting string representation--it won't throw exception if attrs.get() returns null, which may happen if attribute is not found:

unique_members[i] = Objects.toString(attrs.get("uniqueMember"));
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
0

If you came here searching for how to convert any Object with its attributes to a string, you can consider using ReflectionToStringBuilder:

ReflectionToStringBuilder.toString(anyObject);
serv-inc
  • 35,772
  • 9
  • 166
  • 188