本文整理匯總了Java中com.sun.source.tree.VariableTree.getInitializer方法的典型用法代碼示例。如果您正苦於以下問題:Java VariableTree.getInitializer方法的具體用法?Java VariableTree.getInitializer怎麽用?Java VariableTree.getInitializer使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.sun.source.tree.VariableTree
的用法示例。
在下文中一共展示了VariableTree.getInitializer方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: testPreferredPositionForBinaryOp
import com.sun.source.tree.VariableTree; //導入方法依賴的package包/類
@Test
void testPreferredPositionForBinaryOp() throws IOException {
String code = "package test; public class Test {"
+ "private void test() {"
+ "Object o = null; boolean b = o != null && o instanceof String;"
+ "} private Test() {}}";
CompilationUnitTree cut = getCompilationUnitTree(code);
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(0);
VariableTree condSt = (VariableTree) method.getBody().getStatements().get(1);
BinaryTree cond = (BinaryTree) condSt.getInitializer();
JCTree condJC = (JCTree) cond;
int condStartPos = code.indexOf("&&");
assertEquals("testPreferredPositionForBinaryOp",
condStartPos, condJC.pos);
}
示例2: checkZeroSizeArray
import com.sun.source.tree.VariableTree; //導入方法依賴的package包/類
private static boolean checkZeroSizeArray(CompilationInfo info, TreePath val) {
if (val.getLeaf().getKind() != Tree.Kind.VARIABLE) {
return false;
}
VariableTree vt = (VariableTree)val.getLeaf();
ExpressionTree xpr = vt.getInitializer();
if (xpr == null) {
return false;
}
if (xpr.getKind() == Tree.Kind.NEW_ARRAY) {
NewArrayTree nat = (NewArrayTree)xpr;
List<? extends ExpressionTree> dims = nat.getDimensions();
if (dims != null && !dims.isEmpty()) {
Object size = ArithmeticUtilities.compute(info,
new TreePath(
new TreePath(val, xpr),
dims.get(dims.size() -1)),
true);
return ArithmeticUtilities.isRealValue(size) && Integer.valueOf(0).equals(size);
} else {
return nat.getInitializers() != null && nat.getInitializers().isEmpty();
}
}
return false;
}
示例3: visitVariable
import com.sun.source.tree.VariableTree; //導入方法依賴的package包/類
@Override
public Boolean visitVariable(VariableTree node, ConstructorData p) {
super.visitVariable(node, p);
Element e = info.getTrees().getElement(getCurrentPath());
if (e != null && SUPPORTED_VARIABLES.contains(e.getKind())) {
// note: if the variable does not have an initializer and is not a parameter (inParameters = true),
// the State will receive null as an assignment to indicate an uninitializer
TreePath tp =
node.getInitializer() != null ?
new TreePath(getCurrentPath(), node.getInitializer()) :
inParameters ? getCurrentPath() : null;
recordVariableState(e, tp);
currentMethodVariables.add((Element) e);
TreePath pp = getCurrentPath().getParentPath();
if (pp != null) {
addScopedVariable(pp.getLeaf(), e);
}
}
return null;
}
示例4: isBreakable
import com.sun.source.tree.VariableTree; //導入方法依賴的package包/類
private static boolean isBreakable(TreePath path) {
Tree tree = path.getLeaf();
switch (tree.getKind()) {
case BLOCK:
case ANNOTATION_TYPE:
case CLASS:
case ENUM:
case INTERFACE:
case COMPILATION_UNIT:
case IMPORT:
case MODIFIERS:
case EMPTY_STATEMENT:
return false;
}
while (path != null) {
tree = path.getLeaf();
Tree.Kind kind = tree.getKind();
if (kind == Tree.Kind.IMPORT) return false;
if (kind == Tree.Kind.VARIABLE) {
VariableTree varTree = (VariableTree)tree;
if (varTree.getInitializer() == null) {
return false;
}
}
path = path.getParentPath();
}
return true;
}
示例5: test120768
import com.sun.source.tree.VariableTree; //導入方法依賴的package包/類
public void test120768() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n" +
"\n" +
"public class Test {\n" +
" byte[] test = new byte[10000];\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n" +
"\n" +
"public class Test {\n" +
" byte[] test = new byte[WHAT_A_F];\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.RESOLVED);
CompilationUnitTree cut = workingCopy.getCompilationUnit();
TreeMaker make = workingCopy.getTreeMaker();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
VariableTree var = (VariableTree) clazz.getMembers().get(1);
NewArrayTree nat = (NewArrayTree) var.getInitializer();
workingCopy.rewrite(nat.getDimensions().get(0), make.Identifier("WHAT_A_F"));
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
}
示例6: test162485b
import com.sun.source.tree.VariableTree; //導入方法依賴的package包/類
public void test162485b() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n" +
"\n" +
"public class Test {\n" +
" Object test = new int[] {};\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n" +
"\n" +
"public class Test {\n" +
" Object test = {{1}};\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.RESOLVED);
CompilationUnitTree cut = workingCopy.getCompilationUnit();
TreeMaker make = workingCopy.getTreeMaker();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
VariableTree var = (VariableTree) clazz.getMembers().get(1);
NewArrayTree nat = (NewArrayTree) var.getInitializer();
NewArrayTree dim2 = make.NewArray(null, Collections.<ExpressionTree>emptyList(), Collections.singletonList(make.Literal(Integer.valueOf(1))));
NewArrayTree newTree = make.NewArray(null, Collections.<ExpressionTree>emptyList(), Collections.<ExpressionTree>singletonList(dim2));
workingCopy.rewrite(nat, newTree);
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
}
示例7: testVoidLambdaParameter
import com.sun.source.tree.VariableTree; //導入方法依賴的package包/類
@Test
void testVoidLambdaParameter() throws IOException {
String code = "package t; class Test { " +
"Runnable r = (void v) -> { };" +
"}";
DiagnosticCollector<JavaFileObject> coll =
new DiagnosticCollector<>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
VariableTree field = (VariableTree) clazz.getMembers().get(0);
assertEquals("actual kind: " + field.getInitializer().getKind(),
field.getInitializer().getKind(),
Kind.LAMBDA_EXPRESSION);
LambdaExpressionTree lambda = (LambdaExpressionTree) field.getInitializer();
assertEquals("actual parameters: " + lambda.getParameters().size(),
lambda.getParameters().size(),
1);
Tree paramType = lambda.getParameters().get(0).getType();
assertEquals("actual parameter type: " + paramType.getKind(),
paramType.getKind(),
Kind.PRIMITIVE_TYPE);
TypeKind primitiveTypeKind = ((PrimitiveTypeTree) paramType).getPrimitiveTypeKind();
assertEquals("actual parameter type: " + primitiveTypeKind,
primitiveTypeKind,
TypeKind.VOID);
}
示例8: computeVariableDeclaration
import com.sun.source.tree.VariableTree; //導入方法依賴的package包/類
private static List<? extends TypeMirror> computeVariableDeclaration(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
VariableTree vt = (VariableTree) parent.getLeaf();
if (vt.getInitializer() == error) {
types.add(ElementKind.PARAMETER);
types.add(ElementKind.LOCAL_VARIABLE);
types.add(ElementKind.FIELD);
return Collections.singletonList(info.getTrees().getTypeMirror(new TreePath(parent, vt.getType())));
}
TreePath context = parent.getParentPath();
if (vt.getType() != error || context == null) {
return null;
}
switch (context.getLeaf().getKind()) {
case ENHANCED_FOR_LOOP:
ExpressionTree iterableTree = ((EnhancedForLoopTree) context.getLeaf()).getExpression();
TreePath iterablePath = new TreePath(context, iterableTree);
TypeMirror type = getIterableGenericType(info, iterablePath);
types.add(ElementKind.LOCAL_VARIABLE);
return Collections.singletonList(type);
default:
types.add(ElementKind.CLASS);
return Collections.<TypeMirror>emptyList();
}
}
示例9: run
import com.sun.source.tree.VariableTree; //導入方法依賴的package包/類
public List<Fix> run(CompilationInfo info,
String diagnosticKey,
int offset,
TreePath treePath,
Data<Void> data) {
List<Fix> result = new ArrayList<Fix>();
TypeMirror[] tm = new TypeMirror[1];
TypeMirror[] expressionType = new TypeMirror[1];
Tree[] leaf = new Tree[1];
computeType(info, offset, tm, expressionType, leaf);
if (leaf[0] instanceof VariableTree) {
if (tm[0] != null) {
// special hack: if the reported path is lambda assigned to the variable, do not offer anything:
// I don't know how to compute the desired var type for lambda (lambdas are attributed with respect to the environment) or what the
// proper lambda type should be.
VariableTree vt = (VariableTree)leaf[0];
if (treePath != null && treePath.getLeaf() == vt.getInitializer() && treePath.getLeaf().getKind() == Tree.Kind.LAMBDA_EXPRESSION) {
return null;
}
//anonymous class?
expressionType[0] = org.netbeans.modules.java.hints.errors.Utilities.convertIfAnonymous(expressionType[0]);
result.add(new ChangeTypeFix(info.getJavaSource(),
((VariableTree) leaf[0]).getName().toString(),
Utilities.getTypeName(info, expressionType[0], false).toString(), offset));
}
}
return result;
}
示例10: visitVariable
import com.sun.source.tree.VariableTree; //導入方法依賴的package包/類
@Override
public List<? extends TypeMirror> visitVariable(VariableTree node, Object p) {
if (theExpression == null) {
if (node.getInitializer() == null) {
return null;
}
initExpression(node.getInitializer());
}
if (theExpression.getLeaf() == node.getInitializer()) {
// the expression must be assiganble to the variable.
this.expectedTree = new TreePath(getCurrentPath(), node.getType());
return Collections.singletonList(info.getTrees().getTypeMirror(getCurrentPath()));
}
return null;
}
示例11: testEmptyStaticBlockSemicolon
import com.sun.source.tree.VariableTree; //導入方法依賴的package包/類
public void testEmptyStaticBlockSemicolon() throws Exception{
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package tohle;\n" +
"\n" +
"public class Main {\n" +
"\n" +
" static enum Whorehouse {\n" +
" /** first prostitute */\n" +
" PrvniDevka,\n" +
" /** second prostitue */\n" +
" DruhaDevka,\n" +
" /** third prostitute */\n" +
" TretiDevka;\n" +
" };\n" + // the semicolon is strange here -- shouldn't be there,
" \n" + // but it is correct and we have to handle such a situation
" void method() {\n" +
" Object o = null;\n" +
" String s = o;\n" +
" }\n" +
"}\n");
String golden =
"package tohle;\n" +
"\n" +
"public class Main {\n" +
"\n" +
" static enum Whorehouse {\n" +
" /** first prostitute */\n" +
" PrvniDevka,\n" +
" /** second prostitue */\n" +
" DruhaDevka,\n" +
" /** third prostitute */\n" +
" TretiDevka;\n" +
" };\n" +
" \n" +
" void method() {\n" +
" Object o = null;\n" +
" String s = (String) o;\n" +
" }\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException{
workingCopy.toPhase(Phase.RESOLVED);
TreeMaker make = workingCopy.getTreeMaker();
CompilationUnitTree cut = workingCopy.getCompilationUnit();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(2);
VariableTree var = (VariableTree) method.getBody().getStatements().get(1);
ExpressionTree init = var.getInitializer();
ExpressionTree cast = make.TypeCast(make.Identifier("String"), init);
workingCopy.rewrite(init, cast);
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
}
示例12: testAddCastToDeclStmt
import com.sun.source.tree.VariableTree; //導入方法依賴的package包/類
public void testAddCastToDeclStmt() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"import java.util.*;\n\n" +
"public class Test<E> {\n" +
" public void taragui() {\n" +
" System.err.println(\"taragui() method\");\n" +
" String s = \"Oven.\";\n" +
"// line comment\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"import java.util.*;\n\n" +
"public class Test<E> {\n" +
" public void taragui() {\n" +
" System.err.println(\"taragui() method\");\n" +
" String s = (String) \"Oven.\";\n" +
"// line comment\n" +
" }\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.RESOLVED);
CompilationUnitTree cut = workingCopy.getCompilationUnit();
TreeMaker make = workingCopy.getTreeMaker();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(1);
VariableTree var = (VariableTree) method.getBody().getStatements().get(1);
ExpressionTree init = var.getInitializer();
ExpressionTree cast = make.TypeCast(make.Identifier("String"), init);
workingCopy.rewrite(init, cast);
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
}
示例13: visitVariable
import com.sun.source.tree.VariableTree; //導入方法依賴的package包/類
@Override
public Void visitVariable(VariableTree tree, Map<String, Object> p) {
scan(tree.getModifiers(), p);
if (tree.getType() != null && tree.getType().getKind() == Kind.IDENTIFIER) {
p.put("request", null);
}
scan(tree.getType(), p);
Union2<String, DeclaredType> leftSide = (Union2<String, DeclaredType>) p.remove("result");
p.remove("request");
Union2<String, DeclaredType> rightSide = null;
if (leftSide != null && tree.getInitializer() != null) {
Element el = info.getTrees().getElement(new TreePath(getCurrentPath(),tree.getInitializer()));
TypeMirror rightType = el != null ? el.asType() : null;
// System.err.println("rightType = " + rightType );
// System.err.println("tree.getInitializer()=" + tree.getInitializer());
// System.err.println("rightType.getKind()=" + rightType.getKind());
// System.err.println("INVALID_TYPES.contains(rightType.getKind())=" + INVALID_TYPES.contains(rightType.getKind()));
if (rightType != null && rightType.getKind() == TypeKind.DECLARED) {
rightSide = Union2.<String, DeclaredType>createSecond((DeclaredType) rightType);
} else {
if (tree.getInitializer().getKind() == Kind.NEW_CLASS || tree.getInitializer().getKind() == Kind.NEW_ARRAY) {
p.put("request", null);
}
}
}
scan(tree.getInitializer(), p);
rightSide = rightSide == null ? (Union2<String, DeclaredType>) p.remove("result") : rightSide;
p.remove("result");
// System.err.println("rightSide = " + rightSide );
p.remove("request");
if (leftSide != null && rightSide != null) {
if (!(leftSide instanceof TypeMirror) || !(rightSide instanceof TypeMirror)) {
hints.add(new TypeHint(leftSide, rightSide));
}
}
return null;
}
示例14: testAddCast94324
import com.sun.source.tree.VariableTree; //導入方法依賴的package包/類
public void testAddCast94324() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package javaapplication3;\n" +
"\n" +
"public class Klasa {\n" +
" \n" +
" static Object method() {\n" +
" return null;\n" +
" }\n" +
" \n" +
" public static void main(String[] args) {\n" +
" // TODO code application logic here\n" +
" String s = Klasa.method();\n" +
" }\n" +
"\n" +
"}\n"
);
String golden =
"package javaapplication3;\n" +
"\n" +
"public class Klasa {\n" +
" \n" +
" static Object method() {\n" +
" return null;\n" +
" }\n" +
" \n" +
" public static void main(String[] args) {\n" +
" // TODO code application logic here\n" +
" String s = (String) Klasa.method();\n" +
" }\n" +
"\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.RESOLVED);
CompilationUnitTree cut = workingCopy.getCompilationUnit();
TreeMaker make = workingCopy.getTreeMaker();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(2);
VariableTree var = (VariableTree) method.getBody().getStatements().get(0);
ExpressionTree init = var.getInitializer();
ExpressionTree cast = make.TypeCast(make.Identifier("String"), init);
workingCopy.rewrite(init, cast);
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
System.err.println(res);
assertEquals(golden, res);
}
示例15: collectEntities
import com.sun.source.tree.VariableTree; //導入方法依賴的package包/類
private FieldInitEntities collectEntities(ClassTree tree, VisitorState state) {
Symbol.ClassSymbol classSymbol = ASTHelpers.getSymbol(tree);
Set<Symbol> nonnullInstanceFields = new LinkedHashSet<>();
Set<Symbol> nonnullStaticFields = new LinkedHashSet<>();
List<BlockTree> instanceInitializerBlocks = new ArrayList<>();
List<BlockTree> staticInitializerBlocks = new ArrayList<>();
Set<MethodTree> constructors = new LinkedHashSet<>();
Set<MethodTree> instanceInitializerMethods = new LinkedHashSet<>();
Set<MethodTree> staticInitializerMethods = new LinkedHashSet<>();
// we assume getMembers() returns members in the same order as the declarations
for (Tree memberTree : tree.getMembers()) {
switch (memberTree.getKind()) {
case METHOD:
// check if it is a constructor or an @Initializer method
MethodTree methodTree = (MethodTree) memberTree;
Symbol.MethodSymbol symbol = ASTHelpers.getSymbol(methodTree);
if (isConstructor(methodTree)) {
constructors.add(methodTree);
} else if (isInitializerMethod(state, symbol)) {
if (symbol.isStatic()) {
staticInitializerMethods.add(methodTree);
} else {
instanceInitializerMethods.add(methodTree);
}
}
break;
case VARIABLE:
// field declaration
VariableTree varTree = (VariableTree) memberTree;
Symbol fieldSymbol = ASTHelpers.getSymbol(varTree);
if (fieldSymbol.type.isPrimitive() || skipDueToFieldAnnotation(fieldSymbol)) {
continue;
}
if (varTree.getInitializer() != null) {
// note that we check that the initializer does the right thing in
// matchVariable()
continue;
}
if (fieldSymbol.isStatic()) {
nonnullStaticFields.add(fieldSymbol);
} else {
nonnullInstanceFields.add(fieldSymbol);
}
break;
case BLOCK:
// initializer block
BlockTree blockTree = (BlockTree) memberTree;
if (blockTree.isStatic()) {
staticInitializerBlocks.add(blockTree);
} else {
instanceInitializerBlocks.add(blockTree);
}
break;
case ENUM:
case CLASS:
case INTERFACE:
case ANNOTATION_TYPE:
// do nothing
break;
default:
throw new RuntimeException(memberTree.getKind().toString() + " " + memberTree);
}
}
return FieldInitEntities.create(
classSymbol,
ImmutableSet.copyOf(nonnullInstanceFields),
ImmutableSet.copyOf(nonnullStaticFields),
ImmutableList.copyOf(instanceInitializerBlocks),
ImmutableList.copyOf(staticInitializerBlocks),
ImmutableSet.copyOf(constructors),
ImmutableSet.copyOf(instanceInitializerMethods),
ImmutableSet.copyOf(staticInitializerMethods));
}