【发布时间】:2016-11-23 16:50:13
【问题描述】:
我的属性有点问题。我目前正在从事一个项目,该项目将来自 LDAP 服务器的电子邮件解析为 Java 应用程序,该应用程序将在未来对电子邮件做一些有趣的事情。
我目前正在使用此代码从 LDAP 上的用户那里获取电子邮件,并且它需要将电子邮件放入 User 类中,如我的代码所示:
[some code here, TRY CATCH is also included]
LdapContext ctx = new InitialLdapContext(env, null);
ctx.setRequestControls(null);
NamingEnumeration<?> namingEnum2 = ctx.search("[path to the server]", "(objectClass=user)", getSimpleSearchControls());
System.out.println("Test: print emails from whole DIRECOTRY: \n");
while (namingEnum2.hasMore()) {
SearchResult result = (SearchResult) namingEnum2.next();
Attributes attrs = result.getAttributes();
System.out.println(attrs.get("mail"));
/** This line above works fine, but every time there is no email
in User info, it prints "null" in some cases when there is
no email, which is not perfect. But this is just here to see
if everything works and indeed it does.**/
/**User Class accepts a String parameter, checks if it's empty
and all that, does some checking and etc... BUT! attrs.get("mail")
is an Attribute, NOT a String. And I need to somehow "cast" this
attribute to a String, so I can work with it.**/
User user = new User(attrs.get("mail")); //error yet,because the parameter is not a String.
User user = new User(attrs.get("mail").toString());//gives an expeption.
/** And I know that there is a toString() method in Attribute Class,
but it doesn't work, it gives an "java.lang.NullPointerException"
exception when I use it as attrs.get("mail").toString() **/
}
这是 User 类的构造函数:
public User(String mail){
eMail = "NO EMAIL!";
if (mail != null && !mail.isEmpty()){
eMail = mail;
}
else
{
eMail = "NO EMAIL!";
}
}
【问题讨论】:
-
您能否以可读的方式格式化您的代码,使其具有一致的缩进并且没有大量的任意空行?它目前看起来像是掉在地板上。
-
.toString() 给出异常,因为 attrs.get("mail") 本身返回 null
-
为什么我的问题评分这么低?这不像是一个超级愚蠢的问题,比如“如何在 JavaScript 或 Java 的控制台中打印出“Hello World”,同样的事情 lul”。我的代码格式并不完美,但仍然可读。有很多其他俄罗斯程序员的 cmet 我不得不删除,所以你们不要介意。问我的问题是我做错了吗?
-
一些避免对您的问题产生负面反应的建议:1)努力正确格式化您的代码(不仅仅是可以忍受的); 2)发布minimal, complete, verifiable example而不是代码片段; 3)发布任何异常的堆栈跟踪; 4)在你的问题中清楚地描述你的问题,而不是隐藏在代码里面的 cmets 中。不做这些事情就是将自己的精力转移到您寻求帮助的人身上。
-
@khelwood 好的,这是有道理的。