Java/Reflection/Identifier — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 06:02, 1 июня 2010
Содержание
- 1 Check whether the given String is a valid identifier according to the Java Language specifications.
- 2 Determines if the specified string is permissible as a Java identifier.
- 3 Determine whether the supplied string represents a well-formed fully-qualified Java classname.
- 4 Escape Java Literal
- 5 Is Java Identifier and get Java Identifier
- 6 To Identifier String
Check whether the given String is a valid identifier according to the Java Language specifications.
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Map;
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
public class Main{
/**
* Check whether the given String is a valid identifier according
* to the Java Language specifications.
*
* See The Java Language Specification Second Edition, Section 3.8
* for the definition of what is a valid identifier.
*
* @param s String to check
*
* @return <code>true</code> if the given String is a valid Java
* identifier, <code>false</code> otherwise.
*/
public final static boolean isValidJavaIdentifier(String s)
{
// an empty or null string cannot be a valid identifier
if (s == null || s.length() == 0)
{
return false;
}
char[] c = s.toCharArray();
if (!Character.isJavaIdentifierStart(c[0]))
{
return false;
}
for (int i = 1; i < c.length; i++)
{
if (!Character.isJavaIdentifierPart(c[i]))
{
return false;
}
}
return true;
}
}
Determines if the specified string is permissible as a Java identifier.
/*
* Copyright 2005 Joe Walker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class Main {
/**
* Determines if the specified string is permissible as a Java identifier.
* Returns true if the string is non-null, non-zero length with a Java
* identifier start as the first character and Java identifier parts in all
* remaining characters.
* @param test the string to be tested.
* @return true if the string is a Java identifier, false otherwise.
* @see java.lang.Character#isJavaIdentifierPart(char)
* @see java.lang.Character#isJavaIdentifierStart(char)
*/
public static boolean isJavaIdentifier(String test)
{
if (test == null || test.length() == 0)
{
return false;
}
if (!Character.isJavaIdentifierStart(test.charAt(0)) && test.charAt(0) != "_")
{
return false;
}
for (int i = 1; i < test.length(); i++)
{
if (!Character.isJavaIdentifierPart(test.charAt(i)) && test.charAt(i) != "_")
{
return false;
}
}
return true;
}
}
Determine whether the supplied string represents a well-formed fully-qualified Java classname.
/*
* JBoss DNA (http://www.jboss.org/dna)
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
* See the AUTHORS.txt file in the distribution for a full listing of
* individual contributors.
*
* JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
* is licensed to you under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* JBoss DNA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
public class Utils {
/**
* Determine whether the supplied string represents a well-formed fully-qualified Java classname. This utility method enforces
* no conventions (e.g., packages are all lowercase) nor checks whether the class is available on the classpath.
*
* @param classname
* @return true if the string is a fully-qualified class name
*/
public static boolean isFullyQualifiedClassname( String classname ) {
if (classname == null) return false;
String[] parts = classname.split("[\\.]");
if (parts.length == 0) return false;
for (String part : parts) {
CharacterIterator iter = new StringCharacterIterator(part);
// Check first character (there should at least be one character for each part) ...
char c = iter.first();
if (c == CharacterIterator.DONE) return false;
if (!Character.isJavaIdentifierStart(c) && !Character.isIdentifierIgnorable(c)) return false;
c = iter.next();
// Check the remaining characters, if there are any ...
while (c != CharacterIterator.DONE) {
if (!Character.isJavaIdentifierPart(c) && !Character.isIdentifierIgnorable(c)) return false;
c = iter.next();
}
}
return true;
}
}
Escape Java Literal
/*
* Static String formatting and query routines.
* Copyright (C) 2001-2005 Stephen Ostermiller
* http://ostermiller.org/contact.pl?regarding=Java+Utilities
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* See COPYING.TXT for details.
*/
import java.util.HashMap;
import java.util.regex.Pattern;
/**
* Utilities for String formatting, manipulation, and queries.
* More information about this class is available from .
*
* @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities
* @since ostermillerutils 1.00.00
*/
public class StringHelper {
/**
* Replaces characters that are not allowed in a Java style
* string literal with their escape characters. Specifically
* quote ("), single quote ("), new line (\n), carriage return (\r),
* and backslash (\), and tab (\t) are escaped.
*
* @param s String to be escaped
* @return escaped String
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.00.00
*/
public static String escapeJavaLiteral(String s){
int length = s.length();
int newLength = length;
// first check for characters that might
// be dangerous and calculate a length
// of the string that has escapes.
for (int i=0; i<length; i++){
char c = s.charAt(i);
switch(c){
case "\"":
case "\"":
case "\n":
case "\r":
case "\t":
case "\\":{
newLength += 1;
} break;
}
}
if (length == newLength){
// nothing to escape in the string
return s;
}
StringBuffer sb = new StringBuffer(newLength);
for (int i=0; i<length; i++){
char c = s.charAt(i);
switch(c){
case "\"":{
sb.append("\\\"");
} break;
case "\"":{
sb.append("\\\"");
} break;
case "\n":{
sb.append("\\n");
} break;
case "\r":{
sb.append("\\r");
} break;
case "\t":{
sb.append("\\t");
} break;
case "\\":{
sb.append("\\\\");
} break;
default: {
sb.append(c);
}
}
}
return sb.toString();
}
}
Is Java Identifier and get Java Identifier
/*
GNU LESSER GENERAL PUBLIC LICENSE
Copyright (C) 2006 The Lobo Project
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact info: lobochief@users.sourceforge.net
*/
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
public class Strings
{
private static final MessageDigest MESSAGE_DIGEST;
public static final String[] EMPTY_ARRAY = new String[0];
static {
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
} catch(NoSuchAlgorithmException err) {
throw new IllegalStateException();
}
MESSAGE_DIGEST = md;
}
public static boolean isBlank(String text) {
return text == null || "".equals(text);
}
public static int countLines(String text)
{
int startIdx = 0;
int lineCount = 1;
for(;;)
{
int lbIdx = text.indexOf("\n", startIdx);
if(lbIdx == -1)
{
break;
}
lineCount++;
startIdx = lbIdx + 1;
}
return lineCount;
}
public static boolean isJavaIdentifier(String id)
{
if(id == null)
{
return false;
}
int len = id.length();
if(len == 0)
{
return false;
}
if(!Character.isJavaIdentifierStart(id.charAt(0)))
{
return false;
}
for(int i = 1; i < len; i++)
{
if(!Character.isJavaIdentifierPart(id.charAt(i)))
{
return false;
}
}
return true;
}
public static String getJavaStringLiteral(String text) {
StringBuffer buf = new StringBuffer();
buf.append(""");
int len = text.length();
for(int i = 0; i < len; i++) {
char ch = text.charAt(i);
switch(ch) {
case "\\":
buf.append("\\\\");
break;
case "\n":
buf.append("\\n");
break;
case "\r":
buf.append("\\r");
break;
case "\t":
buf.append("\\t");
break;
case """:
buf.append("\\\"");
break;
default:
buf.append(ch);
break;
}
}
buf.append(""");
return buf.toString();
}
public static String getJavaIdentifier(String candidateID) {
int len = candidateID.length();
StringBuffer buf = new StringBuffer();
for(int i = 0; i < len; i++)
{
char ch = candidateID.charAt(i);
boolean good = i == 0 ? Character.isJavaIdentifierStart(ch) : Character.isJavaIdentifierPart(ch);
if(good)
{
buf.append(ch);
}
else {
buf.append("_");
}
}
return buf.toString();
}
}
To Identifier String
/*
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://wingsframework.org).
*
* wingS is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* Please see COPYING for the complete licence.
*/
import java.util.StringTokenizer;
/**
* Some string manipulation utilities.
*
* @author
*/
public class StringUtil {
private final static char[] ALPHAS = {
"a", "b",
"c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z",
};
/**
* All possible digits for representing a number as a String
* This is conservative and does not include "special"
* characters since some browsers don"t handle them right.
* The IE for instance seems to be case insensitive in class
* names for CSSs. Grrr.
*/
private final static char[] DIGITS = {
"0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b",
"c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z",
/* This %@&!-IE is case insensitive for certain
* URLs and IDs
* "A" , "B" ,
* "C" , "D" , "E" , "F" , "G" , "H" ,
* "I" , "J" , "K" , "L" , "M" , "N" ,
* "O" , "P" , "Q" , "R" , "S" , "T" ,
* "U" , "V" , "W" , "X" , "Y" , "Z"
*/
};
public static final int MAX_RADIX = DIGITS.length;
/**
* creates a shortest possible string representation of the given
* long number that qualifies as an identifier in common programming
* languages (and HTML-id"s :-)
* That is, it must start with a letter.
*
* @param val the long value to be encoded
* @return a string represantation of the given value that qualifies
* as an identifier.
*/
public static String toIdentifierString(long val) {
char buf[] = new char[14];
int i = 0;
if (val < 0) {
buf[i++] = "_";
val = -(val + 1);
}
buf[i++] = ALPHAS[(int) (val % ALPHAS.length)];
val /= ALPHAS.length;
while (val != 0 && i < buf.length) {
buf[i++] = DIGITS[(int) (val % DIGITS.length)];
val /= DIGITS.length;
}
return new String(buf, 0, i);
}
}